<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2016/8/11
 * Time: 14:01
 */
namespace SDXApi\Model;
use SDXApi\Repositories\BuyNowGoodsRepository;
use SDXApi\Service\BuyNowGoodsService;
use SDXApi\Service\PromoteService;
use SDXApi\Service\Kingdee\KingdeeService;
use Think\Model;

class NewCartModel extends Model
{
    protected $tableName = 'cart';


    public function uid_favourable_list($uid){
        //获取当前用户等级
        $user_rank = D('users')->where(array('user_id'=>$uid))->getField('user_rank');
        $now = gmtime();

        $map = array();

        $map["start_time"] = array('elt',$now);
        $map["end_time"] = array('egt',$now);
        $map['act_type'] = array('in',array(FAT_GOODS,FAT_PRICE,FAT_DISCOUNT));
        $map['_string'] = "FIND_IN_SET(".$user_rank.", user_rank)";

        //获取当前用户可参与的活动（除抢购外）
        $favourable_activity_list = M('favourable_activity')->where($map)->select();
        return $favourable_activity_list;

    }

    /**
     * 获取购物车商品
     * @param $uid
     * @param $wid
     * @param int $rec_ids
     * @param array $favourable_list
     * @param int $flow_type
     * @param bool $refresh
     * @return array
     */
    public function get_cart_goods($uid,$wid,$rec_ids=0,$favourable_list=array(),$flow_type=CART_GENERAL_GOODS,$refresh=0){
        $cart_goods = $this->get_cart_goods_by_uid($uid,$wid,$rec_ids,$flow_type);
        //是否检查更新购物车商品价格
        if($refresh){
            $this->check_goods_price($cart_goods,$uid,false);
            $cart_goods = $this->get_cart_goods_by_uid($uid,$wid,$rec_ids,$flow_type);
        }

        $cart_goods=$this->reset_goods_k3_inventory($wid,$cart_goods);

        $res = array();
        if(!empty($cart_goods)){
            //处理购物车中的商品活动数据
            $cart_goods = $this->convert_cart_goods($cart_goods, $favourable_list,true);
            //计算购物车金额以及优惠
            $res = $this->get_cart_total($cart_goods,$favourable_list,$uid,true);
        }
        return $res;
    }


    public function reset_goods_k3_inventory($wid,$cart_goods){
        if(in_array($wid,C('K3_Wid'))) {
            $goods_sn_list = array();
            foreach ($cart_goods as $g_k => $g_v) {
                $goods_sn_list[] = $g_v['goods_sn'];
            }
            $kingDee = new KingdeeService();
            $goods_practical_num = $kingDee->getGoodsStockByGoodsSn($wid, $goods_sn_list);
            $goodsstorage_list_k3 = $goods_practical_num['data'];

            foreach ($cart_goods as $g_k => $g_v) {
                isset($goodsstorage_list_k3[$g_v['goods_sn']]) ? $cart_goods[$g_k]['practical_num'] = $goodsstorage_list_k3[$g_v['goods_sn']] : $cart_goods[$g_k]['practical_num'] = 0;
            }
        }

        return $cart_goods;
    }


    /**
     * 获取用户购物车商品
     * @param $uid
     * @param $wid
     * @param int $rec_ids
     * @param int $flow_type
     * @return mixed
     */
    public function get_cart_goods_by_uid($uid,$wid,$rec_ids=0,$flow_type=CART_GENERAL_GOODS){
        global $is_cashier;
        global $cashier_id;
        $map = array();
        if($rec_ids){
            $map['c.rec_id'] = array('in',$rec_ids);
        }

        $user_rank = M('user_rank')->where(array('rank_id'=>2))->find();

        $map['c.is_cashier'] = $is_cashier;
        $map['c.cashier_id'] = $cashier_id;
        $map['c.user_id'] = $uid;
        $map['c.rec_type'] = $flow_type;
        $map['mp.user_rank'] = 2;
        if($is_cashier!=1){
            $map['g.is_offline'] = 0;	//排除线下销售商品
        }

        $cart = D('cart');
        $cart_goods = $cart->alias("c")
            ->field("bg.online_safe_inventory,g.is_negative_to_sell,g.negative_to_sell_start_time,g.negative_to_sell_end_time,bg.negative_to_sell_deliverytime_start_time,bg.negative_to_sell_deliverytime_end_time,bg.supplier_code,bg.consignment,c.*,IFNULL(mp.user_price,g.shop_price*(".$user_rank['discount']."/100)) as vip_price,g.shop_price,IF(c.parent_id, c.parent_id, c.goods_id) AS pid,g.cat_id,g.brand_id,g.goods_weight,g.spec_value,g.spec_unit,g.is_presell,g.delivery_type,g.delivery_cycle,g.min_buy_num,g.goods_number as goods_stock,g.goods_thumb,g.goods_img,g.goods_brief,g.is_on_sale,g.is_delete,g.promote_price,g.promote_end_date,g.promote_start_date,g.practical_num,g.is_auto_morrow_presell,g.is_buynow, g.promote_goods_number, g.promote_today_number,g.promote_user_rank,g.offline_can_buy,".$wid." as wid")
            ->join("left join ".C('DB_PREFIX')."goods bg on c.goods_id=bg.goods_id")
            ->join("left join ".C('DB_PREFIX')."goods_wid_".$wid." g on c.goods_id=g.goods_id")
            ->join("left join ".C('DB_PREFIX')."member_price mp on g.goods_id = mp.goods_id")
            ->where($map)
            ->group("c.rec_id")
            ->order("c.giving asc,c.rec_id desc")
            ->select();
        return $cart_goods;
    }

    /*
     * 普通商品购物车价格变动检查
     */
    private function check_normal_price($goods,$uid,$user_rank){
        $result = array('have_change'=>0);
        $map = array();
        $spec = "";
        if($goods['goods_attr_id']){
            $spec = explode(',', $goods['goods_attr_id']);
        }
        $goods_price = D('Goods')->get_final_price($goods['goods_id'], $goods['goods_number'], true, $spec, $uid);
        if($goods_price-$goods['goods_price']!=0){

            M('cart')->where(array('rec_id'=>$goods['rec_id']))->setField('goods_price',$goods_price);
            $goods['new_goods_price'] = $goods_price;
            $result['have_change'] = 1;
            $result['cart_goods'] = $goods;
        }

        return $result;
    }


    /**
     * 活动商品购物车价格变动检查
     * @param $goods
     * @param $user_rank
     * @param $act_list
     * @param $act_type
     * @return array
     */
    public function check_giving_price($goods,$user_rank,$act_list,$act_type){
        $result = array('have_change'=>0);
        $act_info=$this->get_activityinfo($goods['act_id'], $act_list);
        if($act_type=='giving'){
            $serarr=unserialize($act_info['gift']);
        }else if($act_type=='quota'){
            $serarr=unserialize($act_info['quota']);
        }
        foreach($serarr as $item){
            $goods_id_list[]=$item['id'];
            $goods_price_list[]=$item['price'];
            $goods_list[$item['id']]=$item['price'];
        }
        if(($act_info['act_range']==0 || $act_info['act_range']==1 && in_array($goods['cat_id'],explode(",",$act_info['act_range_ext'])) || $act_info['act_range']==2 && in_array($goods['brand_id'],explode(",",$act_info['act_range_ext'])) || $act_info['act_range']==3 && in_array($goods['goods_id'],explode(",",$act_info['act_range_ext']) && $goods_list[$goods['id']]!=$goods['goods_price']))){
            $goods['new_goods_price'] = $goods_list[$goods['id']];
            $result['have_change'] = 1;
            $result['cart_goods'] = $goods;
        }

        return $result;
    }


    /**
     * 取得购物车商品
     * @param   int     $type   类型：默认普通商品
     * @return  array   购物车商品数组
     */
    public function cart_goods($type = CART_GENERAL_GOODS,$rec_ids='',$uid=0,$wid=0) {
        $where = array("user_id"=>$uid,"rec_type"=>$type);
        if(!empty($rec_ids)){
            $where['rec_id'] = array('in',$rec_ids);
        }

        $arr = M("cart")->field("*,goods_price*goods_number AS subtotal")->where($where)->select();
        /* 格式化价格及礼包商品 */
        foreach ($arr as $key => $value) {
            $arr[$key]['formated_market_price'] = price_format($value['market_price'], false);
            $arr[$key]['formated_goods_price'] = price_format($value['goods_price'], false);
            $arr[$key]['formated_subtotal'] = price_format($value['subtotal'], false);
            if ($value['extension_code'] == 'package_buy') {
                $arr[$key]['package_goods_list'] = $this->get_package_goods($value['goods_id']);
            }
            //             $arr[$key]['goods_total_price'] = $value['goods_price']*$value['goods_number'];
            $arr[$key]['goods_total_price'] = $value['subtotal'];

            $goods = D('goods')->where(array('goods_id'=>$value['goods_id']))->find();
            $arr[$key]['goods_img'] = img_init($goods['goods_img']);
            $arr[$key]['is_auto_morrow_presell'] = $goods['is_auto_morrow_presell'];
            $arr[$key]['virtual_goods_number'] = $goods['goods_number'];
            $is_presell=$goods['is_presell'];
            $goods['is_presell']=(int)$goods['is_presell'];
            if($goods['is_presell']!=0 || $goods['is_negative_to_sell']==1){
                //检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
                $is_presell=D('Goodsstorage')->check_whether_presell($goods['goods_id'],$wid,1);
            }
            if($is_presell){
                $now=date("Y-m-d H:i:s");
                if($goods['is_negative_to_sell']==1 && $goods['negative_to_sell_start_time']<=$now && $goods['negative_to_sell_start_time']>=$now){
                    //负卖
                    $arr[$key]['is_presell']=0;
                    $arr[$key]['goods_stock'] =  $goods['goods_number'];
                }else{
                    $arr[$key]['is_presell']=1;
                    $arr[$key]['goods_stock'] =  $goods['goods_number'];
                    if($goods['delivery_type']==1){  //分段发货
                        $Goodspreselltime=D('Goodspreselltime');
                        if($Goodspreselltime->check_shipping_goodspreselltime($goods['goods_id'])){//检查预售商品是否设置发货配送时间
                            $preselltimeres=$Goodspreselltime->check_shippingtime($goods['goods_id'],time());
                            if($preselltimeres){
                                $arr[$key]['preselltimeres']=$preselltimeres;
                            }else{
                                $arr[$key]['preselltimeres']=array('delivery_time'=>'');
                            }
                        }else{
                            $arr[$key]['preselltimeres']=array('delivery_time'=>'');
                        }
                    }elseif($goods['delivery_type']==2){ //定时方式
                        if($goods['delivery_cycle']>=0){
                            $gmd=local_date('Y-m-d',gmtime());
                            $goods_presell_time = local_date('Y-m-d H:i:s', local_strtotime($gmd.' +'.$goods['delivery_cycle'].' day '.C('DEFAULT_PRESELL_TIME_H')));
                            $arr[$key]['preselltimeres']=array('delivery_time'=>$goods_presell_time);
                        }else{
                            $arr[$key]['preselltimeres']=array('delivery_time'=>'');
                        }
                    }else{
                        $arr[$key]['preselltimeres']=array('delivery_time'=>'');
                    }
                }


            }else{
                $arr[$key]['is_presell']=0;

                if(in_array($wid,C('K3_Wid'))) {
                    $kingDee = new KingdeeService();
                    $goods_practical_num = $kingDee->getGoodsStockByGoodsSn($wid, $goods['goods_sn']);
                    if ($goods_practical_num['status'] != "success") {
                        $goodsstorage['practical_num'] = 0;
                    } else {
                        $goodsstorage['practical_num'] = $goods_practical_num['data'][$goods['goods_sn']];
                    }
                }else{
                    $goodsstorage=D('Goodsstorage')->get_warehous_goods($wid,$goods['goods_id']);
                }

                if($goodsstorage){
                    $arr[$key]['goods_stock']=$goodsstorage['practical_num'];
                }else{
                    $arr[$key]['goods_stock']=0;
                }
                $arr[$key]['preselltimeres']=array('delivery_time'=>'');
            }

            //如果商品名有变动，则修改购物车中的商品名
            if($arr[$key]['goods_name']!=$goods['goods_name']){
                $arr[$key]['goods_name'] = $goods['goods_name'];
                M('cart')->where(array('rec_id'=>$value['rec_id']))->setField('goods_name',$goods['goods_name']);
            }

        }

        return $arr;
    }


    /**
     * 购物车数据统计
     * @param $cart_goods
     * @param $favourable_list
     * @param bool $flag    否根据实际情况实时修改数据，例如：不满足换购或赠送条件时，删除相关的换购商品或赠品
     * @return array
     */
    public function get_cart_total($cart_goods,$favourable_list,$uid,$flag=false,$bonus_id=0){
        $goods_list = array();
        $goods_outstock_list = array();
        $goods_list_total = array(
            'goods_price' => 0, // 本店售价合计（有格式）
            'market_price' => 0, // 市场售价合计（有格式）
            'saving' => 0, // 节省金额（有格式）
            'save_rate' => 0, // 节省百分比
            'goods_amount' => 0, // 本店售价合计（无格式）
            'total_number' => 0,
            'total_vip_price' =>0,
            'cart_total_number' =>0,
            'cart_total_amount' =>0
        );
        $goods_outstock_list_total = array(
            'goods_price' => 0, // 本店售价合计（有格式）
            'market_price' => 0, // 市场售价合计（有格式）
            'saving' => 0, // 节省金额（有格式）
            'save_rate' => 0, // 节省百分比
            'goods_amount' => 0, // 本店售价合计（无格式）
            'total_number' => 0,
            'total_vip_price' =>0
        );

        $cart = D('cart');
        $goodsModel = D('Goods');
        /* 用于统计购物车中实体商品和虚拟商品的个数 */
        $virtual_goods_count = 0;
        $real_goods_count = 0;
        $out_stock_real_goods_count = 0;
        $out_stock_virtual_goods_count = 0;

        $cashier_discount_price=0;

        //计算商品红包比例
        if($bonus_id){
            $bonus_proportion = $this->get_bonus_proportion($cart_goods,$bonus_id);
            $bonus_goods_num=1;
            $bonus_goods_use_amount=0;
        }

        $reduced_price_goods_total = 0;
        foreach ($cart_goods as $key=>$row) {
            //计算折扣价格
            if($row['goods_discount']!=0){
                $old_goods_price=$row['goods_price'];
                $row['goods_price']=round($row['goods_price']*($row['goods_discount']/10),2);
                $cashier_discount_price += ($old_goods_price-$row['goods_price'])*$row['goods_number'];
            }

            //获取初始加入购物车的价格
            $add_cart_price = S('goods_add_cart_price_'.$row['user_id']."_".$row['goods_id']);
            $row['had_reduced_price'] = 0;
            $row['reduced_price']=0;
            if(empty($add_cart_price) && !in_array($row['giving'],array(1,2))){
                S('goods_add_cart_price_'.$row['user_id']."_".$row['goods_id'],$row['goods_price']);
            }else{
                $new_goods_price = D("goods")->get_final_price($row['goods_id'],1,'','',$row['user_id']);
                if($add_cart_price-$new_goods_price>0 && !in_array($row['giving'],array(1,2))){
                    $row['had_reduced_price'] = 1;
                    $row['reduced_price'] = round($add_cart_price-$new_goods_price,2);
                }
            }

            $row['bonus_price']=0;
            //计算符合条件的商品红包的折扣金额
            if($bonus_id && $row['use_bonus']==1){
                $bonus_info = $bonus_proportion['bonus_info'];
                if($bonus_info['bonus_discount_type']==1){
                    $row['bonus_price']=sprintf("%.2f",$row['goods_price']*(1-$bonus_proportion['bonus_goods_proportion']));
                    if($bonus_proportion['bonus_goods_num']==$bonus_goods_num){
                        $row['bonus_price']=sprintf("%.2f",($bonus_proportion['bonus_money']-$bonus_goods_use_amount)/$row['goods_number']);
                    }
//                    $row['goods_price']=sprintf("%.2f",$row['goods_price']-$row['bonus_price']);
                    $bonus_goods_use_amount+=$row['bonus_price']*$row['goods_number'];
                    $bonus_goods_num++;
                }elseif($bonus_info['bonus_discount_type']==2){
                    $row['bonus_price']=sprintf("%.2f",(10-$bonus_info['bonus_money'])/10*$row['goods_price']);
                }
                $row['goods_price']=sprintf("%.2f",$row['goods_price']-$row['bonus_price']);
            }



            /* 查询规格 */
            if (trim($row['goods_attr']) != '') {
                $row['goods_attr'] = addslashes($row['goods_attr']);
                $attr_list = D('goods_attr')->field("attr_value")->where(array('goods_attr_id'=>array("in",$row['goods_attr_id'])))->select();
                foreach ($attr_list as $key=>$attr) {
                    $row['goods_name'] .= ' [' . $attr['attr_value'] . '] ';
                }
            }
            $row['goods_thumb'] = img_init($row['goods_img']);

            //检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
            $now=date("Y-m-d H:i:s");
            if($row['is_presell']!=0 && ($row['is_negative_to_sell'] == 0 || $row['is_negative_to_sell'] == 1 && $row['negative_to_sell_start_time']>$now && $row['negative_to_sell_end_time']<$now)){
                //检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
                if($row['practical_num']-C('rest_goods_number')-$row['online_safe_inventory']>0){
                    $row['is_presell'] = 0;
                }else{
                    $row['is_presell'] = 1;
                }
            }
            $now=date("Y-m-d H:i:s");
            if($row['is_presell']){
                if($row['delivery_type']==1){//分段发货
                    $Goodspreselltime=D('Goodspreselltime');
                    if($Goodspreselltime->check_shipping_goodspreselltime($row['goods_id'])){//检查预售商品是否设置发货配送时间
                        $preselltimeres=$Goodspreselltime->check_shippingtime($row['goods_id'],time());
                        if($preselltimeres){
                            $row['preselltimeres']=array('delivery_time'=>$preselltimeres['delivery_time']);
                        }else{
                            $row['preselltimeres']=array('delivery_time'=>'');
                        }
                    }else{
                        $row['preselltimeres']=array('delivery_time'=>'');
                    }
                }elseif($row['delivery_type']==2){ //定时方式
                    if($row['delivery_cycle']>=0){
                        $gmd=local_date('Y-m-d',gmtime());
                        $goods_presell_time = local_date('Y-m-d H:i:s', local_strtotime($gmd.' +'.$row['delivery_cycle'].' day '.C('DEFAULT_PRESELL_TIME_H')));
                        $row['preselltimeres']=array('delivery_time'=>$goods_presell_time);
                    }else{
                        $row['preselltimeres']=array('delivery_time'=>'');
                    }
                }else{
                    $row['preselltimeres']=array('delivery_time'=>'');
                }
            }elseif(isset($row['is_negative_to_sell']) && $row['is_negative_to_sell'] == 1 && $row['negative_to_sell_start_time']<=$now && $row['negative_to_sell_end_time']>=$now){
                $row['preselltimeres']=array('delivery_time'=>'');
            }else{
                if($row['practical_num']-C('rest_goods_number')>0){
                    $row['goods_stock']=intval($row['practical_num']-C('rest_goods_number'));
                }else{
                    $row['goods_stock']=0;
                }

                $row['preselltimeres']=array('delivery_time'=>'');
            }
            $row['subtotal'] = price_format($row['goods_price'] * $row['goods_number'], false);
            //如果添加到购物车的数量大于库存，则修改为库存数量
            //todo:
            if($row['goods_number']>$row['goods_stock'] && $row['goods_stock']>0 && $row['giving']==0 && $flag==true){
                $res_flag = $cart->where(array('rec_id'=>$row['rec_id']))->setField('goods_number',$row['goods_stock']);
                if($res_flag!==false){
                    $row['goods_number'] = $row['goods_stock'];
                }
            }
            //todo:end
            if($row['spec_value']){

                $row['spec_value'] =  $row['spec_value'];
                $row['spec_unit'] =  $row['spec_unit'];
            }elseif($row['goods_weight']){
                $row['spec_value'] =  $row['goods_weight']*1000;
                $row['spec_unit'] =  "g";
            }
            //计算折扣价格
            if($row['goods_discount']!=0){
                $row['vip_price'] = get_price($row['vip_price']*($row['goods_discount']/10));
            }else{
                $row['vip_price'] = get_price($row['vip_price']);
            }

            $row['true_vip_price'] = get_price($row['vip_price']);
            $current_time = gmtime();
            //拆分购物车中有库存与无库存商品
            $oneDay=86400;//秒
            if($row['goods_stock']>0 && $row['goods_stock'] >= $row['goods_number'] && ($row['is_on_sale']>0 || $row['offline_can_buy']==1) && $row['is_delete']==0 && ($row['expiration_date']==0 || $row['expiration_date']+$oneDay > gmtime())){
                /* 统计实体商品和虚拟商品的个数 */
                if($row['is_check']==1){
                    if ($row['is_real']) {
                        $real_goods_count++;
                    } else {
                        $virtual_goods_count++;
                    }


                    //                    if (floatval($row['goods_price']) <= 0) {
                    //                    	$row['goods_price'] = $row['shop_price'];
                    //					}
                    $goods_list_total['total_number']+=$row['goods_number'];
                    $goods_list_total['goods_price'] += ($row['bonus_price']+$row['goods_price']) * $row['goods_number'];
                    $goods_list_total['market_price'] += $row['market_price'] * $row['goods_number'];
                    $goods_list_total['shop_price'] += $row['shop_price'] * $row['goods_number'];
                    if($row['promote_price']>0 && $row['promote_start_date']<=$current_time && $row['promote_end_date']>=$current_time){
                        $goods_list_total['total_vip_price'] += $row['goods_price'] * $row['goods_number'];
                    }else{
                        $goods_list_total['total_vip_price'] += $row['vip_price'] * $row['goods_number'];
                    }

                }

                $goods_list_total['cart_total_number']+=$row['goods_number'];
                $goods_list_total['cart_total_amount'] += $row['goods_price']*$row['goods_number'];

                if($row['had_reduced_price'] == 1){
                    $reduced_price_goods_total++;
                }
                $goods_list[] = $row;

            }else{
                /* 统计缺货或者已下架实体商品和虚拟商品的个数 */
                if ($row['is_real']) {
                    $out_stock_real_goods_count++;
                } else {
                    $out_stock_virtual_goods_count++;
                }

                //				if (floatval($row['goods_price']) <= 0) {
                //					$row['goods_price'] = $row['shop_price'];
                //				}

                $goods_outstock_list_total['total_number']+=$row['goods_number'];
                $goods_outstock_list_total['goods_price'] += ($row['bonus_price']+$row['goods_price']) * $row['goods_number'];
                $goods_outstock_list_total['market_price'] += $row['market_price'] * $row['goods_number'];
                $goods_outstock_list_total['shop_price'] += $row['shop_price'] * $row['goods_number'];
                $goods_outstock_list_total['total_vip_price'] += $row['vip_price'] * $row['goods_number'];
                if($row['promote_price']>0 && $row['promote_start_date']<=$current_time && $row['promote_end_date']>=$current_time){
                    $goods_outstock_list_total['total_vip_price'] += $row['goods_price'] * $row['goods_number'];
                }else{
                    $goods_outstock_list_total['total_vip_price'] += $row['vip_price'] * $row['goods_number'];
                }
                $goods_outstock_list[] = $row;
            }
        }


        //统计购物车有货商品数量以及金额
        $goods_list_total['goods_amount'] = $goods_list_total['goods_price'];
        $goods_list_total['goods_price'] =  get_price($goods_list_total['goods_price']);
        $goods_list_total['goods_price_format'] = price_format($goods_list_total['goods_price'], false);
        $goods_list_total['market_price_format'] = price_format($goods_list_total['market_price'], false);
        $goods_list_total['real_goods_count'] = $real_goods_count;
        $goods_list_total['virtual_goods_count'] = $virtual_goods_count;



        //统计购物车中缺货商品数量以及金额
        $goods_outstock_list_total['goods_amount'] = $goods_outstock_list_total['goods_price'];
        $goods_outstock_list_total['saving_format'] = price_format($goods_outstock_list_total['market_price'] - $goods_outstock_list_total['goods_price'], false);
        if ($goods_outstock_list_total['market_price'] > 0) {
            $goods_outstock_list_total['save_rate'] = $goods_outstock_list_total['market_price'] ? round(($goods_outstock_list_total['market_price'] - $goods_outstock_list_total['goods_price']) *
                    100 / $goods_outstock_list_total['market_price']) . '%' : 0;
        }
        $goods_outstock_list_total['goods_price_format'] = price_format($goods_outstock_list_total['goods_price'], false);
        $goods_outstock_list_total['market_price_format'] = price_format($goods_outstock_list_total['market_price'], false);
        $goods_outstock_list_total['real_goods_count'] = $out_stock_real_goods_count;
        $goods_outstock_list_total['virtual_goods_count'] = $out_stock_virtual_goods_count;


        array_merge($goods_list, array());
        //购物车中有货商品活动分组以及统计金额

        $goods_total = $this->activity_goods_group($goods_list, $goods_list_total, $favourable_list,$uid,$flag);
        $goods_total['total']['reduced_price_goods_total_num'] = $reduced_price_goods_total;
        $goods_total['total']['goods_price'] += $cashier_discount_price;
        $goods_total['total']['discount'] += $cashier_discount_price;
        return array('goods_list' => $goods_total['goods_list'], 'total' => $goods_total['total'], 'goods_outstock_list'=>$goods_outstock_list,'out_stock_total'=>$goods_outstock_list_total);
    }

    public function get_cart_goods_list($cart_goods_list){
        $goods_list = array();

        //合并购物车商品
        if(!empty($cart_goods_list['favourable_goods'])){
            foreach($cart_goods_list['favourable_goods'] as $f_key=>$f_val){
                if(!empty($f_val['goods_list'])){
                    foreach($f_val['goods_list'] as $fg_key=>$fg_val){
                        $goods_list[] = $fg_val;
                    }
                }
            }
        }

        if(!empty($cart_goods_list['normal_goods'])){
            foreach($cart_goods_list['normal_goods'] as $normal_key=>$normal_val){
                $goods_list[] = $normal_val;
            }
        }

        return $goods_list;
    }

    public function get_cart_goods_list_group($cart_goods_list,$need_convert=true){
        if($need_convert){
            $goods_list = $this->get_cart_goods_list($cart_goods_list);
        }else{
            $goods_list = $cart_goods_list;
        }

        $cart_goods_list_group = array();
        $cart_goods_presell_group = array();    //预售商品组
        $cart_goods_sell_group = array();
        $temp_presell = array();
        foreach($goods_list as $key=>$goods){
            if($goods['is_presell']==1 && !empty($goods['preselltimeres']['delivery_time'])){
                $predate = date('Y-m-d',strtotime($goods['preselltimeres']['delivery_time']));
                $sortkey = strtotime($predate);
                if(!in_array($sortkey,$temp_presell)){
                    $temp_presell[] = strtotime($predate);
                    $cart_goods_presell_group[$sortkey]['shipping_date'] = $predate;
                }
                $cart_goods_presell_group[$sortkey]['goods_list'][] = $goods;
            }else{
                $cart_goods_sell_group[] = $goods;
            }
        }
        krsort($cart_goods_presell_group,SORT_NUMERIC);
        if(!empty($cart_goods_presell_group)){
            foreach($cart_goods_presell_group as $key=>$val){
                $cart_goods_presell_group[$key]['goods_nums'] = count($cart_goods_presell_group[$key]['goods_list']);
            }
            $cart_goods_list_group['has_presell'] = 1;
        }else{
            $cart_goods_list_group['has_presell'] = 0;
        }
        $cart_goods_presell_group = array_values($cart_goods_presell_group);
        $cart_goods_list_group['presell'] = $cart_goods_presell_group;

        $cart_goods_list_group['sell']['goods_list'] = $cart_goods_sell_group;
        $cart_goods_list_group['sell']['goods_nums'] = count($cart_goods_sell_group);

        $cart_goods_list_group['goods_total_number'] = count($goods_list);

        return $cart_goods_list_group;
    }

    public function get_order_goods_list_group($cart_goods_list){
        $goods_list = $cart_goods_list;
        $order_list = array();
        $order_id_temp = array();
        foreach($goods_list as $key=>$goods){
            if(!in_array($goods['order_id'],$order_id_temp)){
                $order_id_temp[] = $goods['order_id'];
                $order_list[$goods['order_id']]['order_sn'] =  $goods['order_sn'];
                $order_list[$goods['order_id']]['sort_key'] =  $goods['best_time_start'];
                $order_list[$goods['order_id']]['shipping_date'] = date('Y-m-d',$goods['best_time_start']);
                $order_list[$goods['order_id']]['order_status'] =  $goods['order_status'];
                $order_list[$goods['order_id']]['shipping_status'] =  $goods['shipping_status'];
                $order_list[$goods['order_id']]['pay_status'] =  $goods['pay_status'];
                $goods['preselltimeres']['delivery_time'] = date('Y-m-d',$goods['best_time_start']);
            }
            $order_list[$goods['order_id']]['goods_list'][] = $goods;
        }

        $goods_list_group = array();
        foreach($order_list as $key=>$order){
            $sort_key[] = $order['sort_key'];
            $order_list[$key]['goods_nums'] = count($order_list[$key]['goods_list']);
        }

        $order_list = array_values($order_list);
        array_multisort($sort_key,SORT_DESC,$order_list);

        $goods_list_group['order_list'] = $order_list;
        $goods_list_group['goods_total_number'] = count($cart_goods_list);
//        dump($order_list);
//        exit;
        return $goods_list_group;
    }

    /**
     * 购物车促销价过期与生效处理
     * Created by Jerry
     * @param $carData
     * @return mixed
     */
    protected function check_promote_price_by_time($carData)
    {
        $goodsModel = D('Goods');
        $carModel = M('Cart');
        $goodsWhere = array(
            'user_id'	=>	array('EQ', $carData['user_id']),
            'rec_id'	=>	array('EQ', $carData['rec_id']),
            'goods_id'	=>	array('EQ', $carData['goods_id']),
        );
        $goodsInfo = $goodsModel->field('promote_goods_number, promote_today_number')->where($goodsWhere)->find();

        $promote_price = bargain_price($carData['promote_price'], $carData['promote_start_date'], $carData['promote_end_date']);

        if ($promote_price > 0 && $carData['giving'] == 0 && $carData['goods_number'] <= $goodsInfo['promote_goods_number'] && $goodsInfo['promote_goods_number'] > 0) {
            //			促销价生效购物车价格未更改
            $saveData = array(
                'goods_price' 	=>	$promote_price,
                'giving'		=>	4,
            );

            $carModel->where($goodsWhere)->save($saveData);
            $carData['goods_price'] = $promote_price;
            $carData['giving'] = 4;
        }
        else if (($promote_price > 0 && $carData['giving'] != 4 && $carData['goods_number'] > $goodsInfo['promote_goods_number'] && $goodsInfo['promote_goods_number'] > 0) || ($promote_price > 0 && $carData['giving'] == 4 && $carData['goods_number'] > $goodsInfo['promote_goods_number'] && $goodsInfo['promote_goods_number'] > 0))
        {
            //			促销价生效购物车价格未更改并超过限购数量
            $saveData = array(
                'goods_price' 	=>	$promote_price,
                'giving'		=>	4,
                'goods_number'	=>	$goodsInfo['promote_goods_number'],
            );

            $carModel->where($goodsWhere)->save($saveData);
            $carData['goods_price'] = $promote_price;
            $carData['giving'] = 4;
            $carData['goods_number'] = $goodsInfo['promote_goods_number'];
        }
        else if ($promote_price == 0 && $carData['giving'] == 4)
        {
            //			促销价失效购物车未更改
            $price = $goodsModel->get_final_price($carData['goods_id'], 1, false, array(), $carData['user_id']);
            $saveData = array(
                'goods_price' 	=>	$price,
                'giving'		=>	0,
            );

            $carModel->where($goodsWhere)->save($saveData);
            $carData['goods_price'] = $price;
            $carData['giving'] = 0;
            $carData['promote_price'] = 0;
            $carData['promote_end_date'] = '';
            $carData['promote_start_date'] = '';
        }
        else if ($promote_price == 0 || ($promote_price == 0 && $carData['giving'] == 0))
        {
            $carData['promote_price'] = 0;
            $carData['promote_end_date'] = '';
            $carData['promote_start_date'] = '';
        }

        return $carData;
    }

    /**
     * 处理购物车促销价
     * Created by Jerry
     * @param array $cartData
     * @return array
     */
    public function checkCartDataPromote($cartData = array())
    {
        $promoteService = new PromoteService();
        $promotePrice = $promoteService->checkPromotePriceRank($cartData['goods_id'], $cartData['user_id']);
        $isPromote = $promoteService->isPromote($cartData['user_id'], $cartData['goods_id'], $cartData['goods_number']);

        $goodsModel = D('Goods');
        $cartModel = M('Cart');

        $goodsWhere = array(
            'goods_id'	=>	$cartData['goods_id'],
        );
        $goodsInfo = $goodsModel->field('promote_goods_number, promote_today_number')->where($goodsWhere)->find();

        $cartWhere = array(
            'user_id'	=>	array('EQ', $cartData['user_id']),
            'rec_id'	=>	array('EQ', $cartData['rec_id']),
            'goods_id'	=>	array('EQ', $cartData['goods_id']),
        );
        if ($promotePrice > 0) {
            $saveData = array();

            if ($cartData['giving'] == 0) {
                $saveData['giving'] = 4;
            }

            //			商品限购
            if ($isPromote === -1) {
                $saveData['goods_price'] = $promotePrice;
                $saveData['goods_number'] = $goodsInfo['promote_goods_number'];

                $cartData['goods_number'] = $goodsInfo['promote_goods_number'];
            }

            //			超过当天限购数量
            if ($isPromote === -2) {
                $cartModel->where($cartWhere)->delete();
                $cartData = array();
            }

            //			超过此次订单限购
            if ($isPromote === -3) {
                $cartModel->where($cartWhere)->delete();
                $cartData = array();
            }

            //			促销价生效
            $price = $cartData['goods_price'] - $promotePrice;
            if ($price > 0) {
                $saveData['goods_price'] = $promotePrice;
            }

            if ((! empty($saveData['goods_price'])) || ($cartData['giving'] != $saveData['giving'])) {
                if (! empty($saveData)) {
                    $cartModel->where($cartWhere)->save($saveData);
                }
            }


        }

        if ($promotePrice == 0) {
            $cartData['promote_end_date'] = '';
            $cartData['promote_start_date'] = '';
            $cartData['promote_price'] = 0;
        }

        if ($promotePrice == 0 && $cartData['giving'] == 4) {
            $cartModel->where($cartWhere)->setField('giving', 0);
        }

        return $cartData;

    }


    /**
     * 商品数据分组
     * @param $goods_list   商品列表
     * @param $total    商品统计数据
     * @param $favourable_list  活动列表
     * @param bool $flag  是否根据实际情况实时修改数据，例如：不满足换购或赠送条件时，删除相关的换购商品或赠品
     * @return array
     */
    public function activity_goods_group($goods_list,$total,$favourable_list,$uid,$flag=false){
        $favourable_goods = array();
        $normal_goods = array();

        foreach ($goods_list as $key=>$goods){
            if($goods['act_id']>0 && $goods['act_id']!=6){
                $activity = $this->get_activityinfo($goods['act_id'], $favourable_list);
                if(!$activity){
                    $normal_goods[] = $goods;
                }else{
                    $favourable_goods[$goods['act_id']]['info'] = $activity;
                    $favourable_goods[$goods['act_id']]['goods_list'][] = $goods;
                }
            }else{
                $normal_goods[] = $goods;
            }
        }

        $cart_goods_list = array();
        $cart_goods_list['favourable_goods'] = $this->get_activity_group_info($favourable_goods,$uid,$flag);
        $cart_goods_list['normal_goods'] = $normal_goods;

        $data = array();
        $data['goods_list'] = $cart_goods_list;
        //计算加入满减，折扣后的金额
        $data['total'] = $this->calculation_amount($total, $cart_goods_list['favourable_goods']);

        return $data;
    }

    /**
     * 统计购物车金额
     * @param $total
     * @param $activity_goods_info
     * @return mixed
     */
    public function calculation_amount($total,$activity_goods_info){
        $discount = 0;

        foreach($activity_goods_info as $act_info){
            $discount+=$act_info['info']['discount'];
        }
        $total['discount'] = get_price($discount);
        $total['goods_amount'] = get_price($total['goods_amount']-$discount);
        $total['goods_amount_format'] = price_format($total['goods_amount'], false);
        $total['total_vip_price'] = get_price($total['total_vip_price']-$discount);
        $total['total_vip_price_format'] = price_format($total['total_vip_price'], false);
        $total['saving'] = get_price($total['market_price'] - $total['goods_amount']);
        $total['saving_format'] = price_format($total['saving'], false);
        $total['save_rate'] = $total['market_price']>0 ? round(($total['market_price'] - $total['goods_amount']) *
                100 / $total['market_price']) . '%' : 0;
        $total['vip_saving'] = get_price($total['market_price'] - $total['total_vip_price']);
        $total['vip_saving_format'] = price_format($total['vip_saving'], false);
        $total['vip_save_rate'] = $total['market_price']>0 ? round(($total['market_price'] - $total['vip_saving']) *
                100 / $total['market_price']) . '%' : 0;
        $total['derivative_price'] = get_price($total['goods_amount']-$total['total_vip_price']);
        $total['derivative_price_format'] = price_format($total['derivative_price'], false);

        return $total;
    }

    /**
     * 获取其中对应的act_id活动的信息
     * @param $act_id
     * @param $favourable_list
     * @return bool
     */
    public function get_activityinfo($act_id,$favourable_list){
        foreach ($favourable_list as $activity){
            if($act_id!=$activity['act_id']){
                continue;
            }else{
                return $activity;
            }
        }
        return false;
    }

    /**
     * 获取购物车中活动信息以及活动相关商品
     * @param $favourable_goods
     * @param $uid
     * @param bool $flag   是否根据实际情况实时修改数据，例如：不满足换购或赠送条件时，删除相关的换购商品或赠品
     * @return array
     */
    public function get_activity_group_info($favourable_goods,$uid,$flag=false){
        $result = array();
        foreach ($favourable_goods as $key=>$val){
            $favourable_info = $val;
            $goods_total_price = 0;
            $goods_total_vip_price = 0;
            $favourable_goods_total_price = 0;
            $favourable_goods_total_vip_price = 0;
            $discount = 0;
            $need_add_price = 0;
            $can_redemption = 0;
            $has_goods = 0; //活动是否有赠品和换购以外的商品
            $has_gift_goods = array();
            $wid = 0;
            foreach ($favourable_info['goods_list'] as $fkey=>$goods){
                $wid = $goods['wid'];
                $goods['vip_price']=sprintf("%.2f",$goods['vip_price']);
                if($goods['is_check']==1){


                    //统计所有选取的商品的总金额
                    $goods_total_price+=($goods['goods_price']+$goods['bonus_price'])*$goods['goods_number'];
                    $goods_total_vip_price+=($goods['vip_price']+$goods['bonus_price'])*$goods['goods_number'];
                    //统计所有选取的参与活动的商品总金额
                    if(!in_array($goods['giving'],array(1,2))){
                        $favourable_goods_total_price += ($goods['goods_price']+$goods['bonus_price'])*$goods['goods_number'];
                        $favourable_goods_total_vip_price += ($goods['vip_price']+$goods['bonus_price'])*$goods['goods_number'];
                        $has_goods = 1;
                    }
                }

                if(in_array($goods['giving'],array(1,2))){
                    $has_gift_goods[$goods['goods_id']] = $goods;
                }
            }

            $is_clean_gift = 0; //是否清除赠品或者换购
            switch ($favourable_info['info'][ 'act_type']){
                case FAT_GOODS:
                    if($favourable_goods_total_price>0 && $favourable_goods_total_price-$favourable_info['info']['min_amount']>=0){
                        $can_redemption=1;
                    }else{
                        $need_add_price = $favourable_info['info']['min_amount']-$favourable_goods_total_price;
                        //如果没有普通商品，则清除赠品和换购商品
                        if(!$has_goods){
                            $is_clean_gift = 1;
                        }
                    }
                    break;
                case FAT_PRICE:
                    if($favourable_goods_total_price>0 && $favourable_goods_total_price-$favourable_info['info']['min_amount']>=0){
                        $discount = $favourable_info['info']['act_type_ext'];
                    }else{
                        $need_add_price = $favourable_info['info']['min_amount']-$favourable_goods_total_price;
                    }
                    break;
                case FAT_DISCOUNT:
                    if($favourable_goods_total_price>0 && $favourable_goods_total_price-$favourable_info['info']['min_amount']>=0){
                        $discount = $goods_total_price * (1 - $favourable_info['info']['act_type_ext'] / 100);
                    }else{
                        $need_add_price = $favourable_info['info']['min_amount']-$favourable_goods_total_price;
                    }
                    break;
                case FAT_DISCOUNT_LIMIT:

                    break;
            }


            $favourable_info['info']['discount_info'] = $favourable_info['info']['discount'];
            $favourable_info['info']['discount'] = $discount;
            $favourable_info['discount'] = $discount;
            $favourable_info['goods_total_price'] = $goods_total_price;
            $favourable_info['goods_total_vip_price'] = $goods_total_vip_price;
            $favourable_info['need_add_price'] = $need_add_price;
            $favourable_info['can_redemption'] = $can_redemption;
            $favourable_info['total_amount'] = sprintf("%.2f",$goods_total_price-$discount);
            $favourable_info['total_vip_amount'] = sprintf("%.2f",$goods_total_vip_price-$discount);

            //如果不满足条件，则删除换购商品跟赠品
            if($flag && $can_redemption==0 && ($need_add_price>0 || $is_clean_gift>0)){
                $delete_cart_favourable_goods = $this->delete_cart_favourable_goods($favourable_info['info']['act_id'],$favourable_info['goods_list'],$uid);
                //复位键
                $favourable_info['goods_list'] = array_merge($delete_cart_favourable_goods);
                $favourable_info['goods_total_price'] = $favourable_goods_total_price;
                $favourable_info['goods_total_vip_price'] = $favourable_goods_total_vip_price;
                $favourable_info['total_amount'] = $favourable_goods_total_price-$discount;
                $favourable_info['total_vip_amount'] = $favourable_goods_total_vip_price-$discount;
            }
            if($favourable_info['info']['act_type']==FAT_GOODS){
                $activity_chang_type=0;
                if($can_redemption==1){
                    $activity_chang_type = 1;
                }elseif($need_add_price>0){
                    $activity_chang_type = 0;
                }
                $favourable_info = $this->check_cart_gift_goods($uid,$favourable_info,$has_gift_goods,$wid,$activity_chang_type,$flag);

            }
            $result[] = $favourable_info;
        }
        return $result;
    }

    /**
     * 检查购物车活动赠品变化
     * @param $uid
     * @param $favourable_info
     * @param $has_gift_goods
     * @param $wid
     * @param $activity_chang_type
     * @param bool $show_return_msg
     * @return mixed
     */
    public function check_cart_gift_goods($uid,$favourable_info,$has_gift_goods,$wid,$activity_chang_type,$show_return_msg=false){
        $has_change = false;

        $favourable_info_gift = $favourable_info['info']['gift'];
        if($activity_chang_type==1){
            if(!empty($favourable_info_gift)){
                $gift_goods = $this->get_gift_goods($favourable_info_gift);
                if(!empty($gift_goods)){
                    if(!empty($has_gift_goods) && empty($has_gift_goods[$gift_goods['id']])){
                        $favourable_info['goods_list'] = $this->delete_cart_favourable_goods($favourable_info['info']['act_id'],$favourable_info['goods_list'],$uid);
                        $new_gift_goods = $this->add_gift_goods_to_cart($gift_goods,$favourable_info,$uid,$wid);
                        if(!empty($new_gift_goods)){
                            $favourable_info['goods_list'][] = $new_gift_goods;
                        }

                    }elseif(empty($has_gift_goods)){
                        $new_gift_goods = $this->add_gift_goods_to_cart($gift_goods,$favourable_info,$uid,$wid);
                        if(!empty($new_gift_goods)){
                            $favourable_info['goods_list'][] = $new_gift_goods;
                        }
                    }
                }
            }
        }else{
            $gift_goods_list = $this->get_act_giving_goods($favourable_info['goods_list'],1);
            if(count($gift_goods_list)>0){
                $favourable_info['goods_list'] = $this->delete_cart_favourable_goods($favourable_info['info']['act_id'],$favourable_info['goods_list'],$uid);
                $has_change = true;
            }
        }
        if(!$show_return_msg && (!empty($new_gift_goods) || $has_change)){
            returnApiError('您购物车商品优惠活动有变化，请返回刷新购物车');
        }else{
            return $favourable_info;
        }
    }

    /**
     * 获取当前购物车中活动商品中的不同giving类型的商品
     * @param $cart_goods_list
     * @param $giving
     * @return array
     */
    private function get_act_giving_goods($cart_goods_list,$giving){
        $goods_list = array();
        foreach($cart_goods_list as $goods){
            if($goods['giving']==$giving){
                $goods_list[] = $goods;
            }
        }
        return $goods_list;
    }

    /**
     * 增加活动赠品到购物车
     * @param $gift_goods
     * @param $favourable_info
     * @param $uid
     * @param $wid
     * @return array|mixed
     */
    public function add_gift_goods_to_cart($gift_goods,$favourable_info,$uid,$wid){
        $goods = array();

        $act_info = $favourable_info['info'];
        $act_goods_list = $favourable_info['goods_list'];
        if($act_info['act_range']==3 && is_numeric($act_info['act_range_ext']) && !empty($gift_goods) && $act_info['act_type']==0 && floatval($act_info['min_amount'])==0 && $gift_goods['price']==0){

            $cart_goods_info = $this->get_act_cart_goods_info($act_goods_list,$act_info['act_range_ext']);
            $num = $cart_goods_info['goods_number'];
            $goods_id = $cart_goods_info['goods_id'];
            //买一赠一
            if($num>$act_info['act_type_ext'] && floatval($act_info['act_type_ext'])!=0){
                $change_num=$act_info['act_type_ext'];
            }else{
                $change_num=$num;
            }
            $change_num1=$change_num;
            if($gift_goods['id']==$goods_id){
                $change_num1=$change_num*2;
            }

            $is_valid_true=$this->check_num_valid($gift_goods['id'],$wid,$change_num1);
            if($is_valid_true['status']){
                $res=$this->change_cart($uid,$gift_goods['id'],$change_num,array(),$wid,$act_info['act_id'],'is_exchange',0);
            }
        }elseif(!empty($gift_goods) && $act_info['act_type']==0 && $gift_goods['price']==0){
            $change_num1=1;

            $num = $this->get_act_cart_goods_tatal_num($act_goods_list,$gift_goods['id']);

            $change_num1 +=$num;

            $is_valid_true=$this->check_num_valid($gift_goods['id'],$wid,$change_num1);
            if($is_valid_true['status']){
                $res=$this->change_cart($uid,$gift_goods['id'],1,array(),$wid,$act_info['act_id'],'is_exchange',0);
            }
        }

        if(!empty($res) && $res['status'] && $res['rec_id'] && $res['change_type']=='add'){
            $rec_ids = array();
            $rec_ids[] = $res['rec_id'];
            $cart_goods_list = $this->get_cart_goods_by_uid($uid,$wid,$rec_ids);

            if(!empty($cart_goods_list)){
                $goods = current($cart_goods_list);
                $goods['promote_end_date'] = '';
                $goods['promote_goods_number'] = 0;
                $goods['promote_price'] = 0;
                $goods['promote_start_date'] = '';
                $goods['promote_today_number'] = 0;
                $goods_activity = array();
                $goods_activity['act_id'] = $act_info['act_id'];
                $goods_activity['act_name'] = $act_info['act_name'];
                $goods_activity['act_tag'] = $act_info['act_tag'];
                $goods_activity['current_act'] = 1;
                $goods['activity_list'][] = $goods_activity;
            }
        }
        return $goods;
    }


    /**
     * 获取购物车活动商品信息
     * @param $cart_goods_list
     * @param $goods_id
     * @return array
     */
    private function get_act_cart_goods_info($cart_goods_list,$goods_id){
        $goods_info = array();
        foreach($cart_goods_list as $goods){
            if($goods['goods_id']==$goods_id){
                $goods_info = $goods;
                break;
            }
        }
        return $goods_info;
    }

    /**
     * 获取购物车中活动商品总数
     * @param $cart_goods_list
     * @param $goods_id
     * @return int
     */
    private function get_act_cart_goods_tatal_num($cart_goods_list,$goods_id){
        $total = 0;
        foreach($cart_goods_list as $goods){
            if($goods['goods_id']==$goods_id){
                $total += $goods['goods_number'];
                break;
            }
        }
        return $total;
    }

    /**
     * 获取活动赠品信息
     * @param $goods_list
     * @return array
     */
    public function get_gift_goods($goods_list){
        $goods = array();
        foreach($goods_list as $key=>$val){
            if($val['price']==0){
                $goods = $val;
                break;
            }
        }
        return $goods;
    }
    /**
     * 删除购物车中的换购与赠品商品
     * @param $act_id
     * @param $goods_list
     * @param $uid
     * @return mixed
     */
    public function delete_cart_favourable_goods($act_id,$goods_list,$uid){
        global $is_cashier;
        global $cashier_id;
        if(!empty($uid) && !empty($act_id)){
            $map = array();
            $map['user_id'] = $uid;
            $map['act_id'] = $act_id;
            $map['giving'] = array(in,array(1,2));
            $map['is_cashier'] = $is_cashier;
            $map['cashier_id'] = $cashier_id;
            $res = M('cart')->where($map)->delete();
            if($res!==false){
                foreach($goods_list as $key=>$goods){
                    if(in_array($goods['giving'],array(1,2))){
                        unset($goods_list[$key]);
                    }
                }
            }
        }
        return $goods_list;
    }
    /**
     * 区分赠送与换购类型，返回对应的标签
     * @param int $act_type
     * @param array $favourable_info_gift
     * @return int $activity_tag
     */
    public function check_activity_tag($act_type,$favourable_info_gift,$act_range,$act_range_ext,$min_amount){
        $is_gift = 0;
        $activity_tag = $act_type;
        //如果兑换商品中有商品价格大于0，则为换购标记
        foreach($favourable_info_gift as $g_key=>$gift){
            if($gift['price']>0){
                $is_gift = 1;
                break;
            }
        }
        if($is_gift==1){
            $activity_tag = 5;
        }

        if($act_range==3 && is_numeric($act_range_ext) && count($favourable_info_gift)==1 && $act_type==0 && $min_amount==0 && $favourable_info_gift[0]['price']==0){
            $activity_tag = 7;
        }

        return $activity_tag;
    }

    /**
     * 处理购物车中商品的活动信息
     * @param array $cart_goods
     * @param array $favourable_list
     * @return array $cart_goods
     */
    public function convert_cart_goods($cart_goods,$favourable_list,$change_data=false){
        $wid = I('post.wid', 8, 'int');
        foreach ($cart_goods as $key=>$val){
            $goods_id = $val['goods_id'];
            $goods_cate = $val['cat_id'];
            $goods_brand= $val['brand_id'];
            //商品可参与的活动列表
            $goods_activity_list = array();

            $is_on_activity = false;
            foreach ($favourable_list as $f_key => $f_avl) {
                //判断促销商品是否可以参加活动
                $promote_goods_allow = false;
                if($cart_goods[$key]['giving']==4){
                    $act_promote_ext = explode(',',$f_avl['act_promote_ext']);
                    if($f_avl['act_promote_goods_type']==1){
                        $promote_goods_allow = true;
                    }elseif($f_avl['act_promote_goods_type']==2 && in_array($goods_id,$act_promote_ext)){
                        $promote_goods_allow = true;
                    }
                }

                //如果当前商品是赠品或者换购商品，只参与一个活动
                if(in_array($cart_goods[$key]['giving'],array(1,2)) && $cart_goods[$key]['act_id'] == $f_avl['act_id']){
                    //商品可参与的活动
                    $goods_activity = array();
                    $goods_activity = $f_avl;
//                    $goods_activity['act_id'] = $f_avl['act_id'];
//                    $goods_activity['act_name'] = $f_avl['act_name'];
//                    $goods_activity['act_tag'] = $f_avl['act_tag'];
                    $goods_activity['current_act'] = 1;
                    $is_on_activity = true;
                    $goods_activity_list[] = $goods_activity;
                }elseif($cart_goods[$key]['giving']==0 || $promote_goods_allow===true && $cart_goods[$key]['giving']!=6){    //普通商品，获取商品的活动信息
                    $act_range_ext = explode(',', $f_avl['act_range_ext']);
                    //如果优惠范围为分类且设置包含子分类，则获取当前设置分类的所有子分类
                    if($f_avl['act_range'] == 1 && $f_avl['is_include_subcategory'] == 1){
                        $act_range_ext = $this->get_sub_cate($act_range_ext);
                    }
                    if ($f_avl['act_range'] == 0 || ($f_avl['act_range'] == 1 && in_array($goods_cate, $act_range_ext)) || ($f_avl['act_range'] == 2 && in_array($goods_brand, $act_range_ext)) || ($f_avl['act_range'] == 3 && in_array($goods_id, $act_range_ext))) {
                        if ($cart_goods[$key]['act_id'] == 0 && $change_data) {
                            $savedata = array();
                            $savedata['act_id'] = $f_avl['act_id'];
                            $this->change_cart_goods_act($cart_goods[$key]['rec_id'], $savedata);
                            $cart_goods[$key]['act_id'] = $f_avl['act_id'];
                        }

                        //商品可参与的活动
                        $goods_activity = array();
                        $goods_activity = $f_avl;
//                        $goods_activity['act_id'] = $f_avl['act_id'];
//                        $goods_activity['act_name'] = $f_avl['act_name'];
//                        $goods_activity['act_tag'] = $f_avl['act_tag'];
                        if ($cart_goods[$key]['act_id'] == $f_avl['act_id']) {
                            $goods_activity['current_act'] = 1;
                            $is_on_activity = true;
                        } else {
                            $goods_activity['current_act'] = 0;
                        }
                        $goods_activity_list[] = $goods_activity;
                    }
                }
            }

            //商品可参与的活动列表
            $cart_goods[$key]['activity_list'] = $goods_activity_list;
            //判断商品是否同时参与多个活动
            if(count($goods_activity_list)>1){
                $cart_goods[$key]['muti_acivity'] = 1;
            }else{
                $cart_goods[$key]['muti_acivity'] = 0;
            }
            if(!$is_on_activity && $change_data){
                //修改当前商品的所属活动
                //如果商品当前的活动已经结束，则恢复为普通的商品状态或修改为参与其他活动
                //如果是赠品或换购商品，则从购物车中删除
                if($cart_goods[$key]['giving']==1 || $cart_goods[$key]['giving']==2){
                    $this->remove_cart_goods($cart_goods[$key]['rec_id']);
                    unset($cart_goods[$key]);
                }else{
                    $data = array();
                    if(count($goods_activity_list)>0 && $cart_goods[$key]['is_quota']==0 && count($goods_activity_list)>0){
                        $act_temp = current($goods_activity_list);
                        $data['act_id'] = $act_temp['act_id'];
                        //                        if(count($act_temp['gift']>0)){
                        //                            $data['is_gift'] = $act_temp['act_id'];
                        //                        }
                    }elseif(count($goods_activity_list)<=0 && $cart_goods[$key]['is_quota']==0){
                        $data['act_id'] = 0;
                        $data['is_gift'] = 0;
                    }
                    $this->change_cart_goods_act($cart_goods[$key]['rec_id'], $data);
                    $cart_goods[$key]['act_id'] =$data['act_id'];
                    $cart_goods[$key]['is_gift'] = $data['is_gift'];
                }
            }

            if ($cart_goods[$key]['is_buynow'] == 0){
                //    			促销价商品处理
                $cart_goods[$key] = $this->checkCartDataPromote($cart_goods[$key]);
                if (empty($cart_goods[$key]['promote_price'])) {
                    $cart_goods[$key]['promote_end_date'] = '';
                    $cart_goods[$key]['promote_start_date'] = '';
                    $cart_goods[$key]['promote_price'] = 0;
                }
            }
            //			秒杀商品处理
            else if ($cart_goods[$key]['is_buynow'] == 1){
                $buyNowGoodsService = new BuyNowGoodsService($cart_goods[$key]['user_id'], $wid);
                $cart_goods[$key] = $buyNowGoodsService->handleBuyNowGoodsDataByCart($cart_goods[$key]);
                $cart_goods[$key]['promote_end_date'] = '';
                $cart_goods[$key]['promote_start_date'] = '';
                $cart_goods[$key]['promote_price'] = 0;
            }

            //判断商品是否过期
            $cart_goods[$key]['is_overdue']=0;
            $cart_goods[$key]['overdue_date'] = '';
            if ($cart_goods[$key]['expiration_date']>0){
                $cart_goods[$key]['overdue_date'] = local_date("Y-m-d",$cart_goods[$key]['expiration_date']);
                $oneDay=86400;//秒
                if($cart_goods[$key]['expiration_date']+$oneDay < gmtime()) {
                    $cart_goods[$key]['is_overdue'] = 1;
                }
            }
        }
        //检测商品的优惠活动是否有变化
        $check_cart_goods_activity = $this->check_cart_goods_act_change($cart_goods);
        if($check_cart_goods_activity['has_change'] && !$change_data){
            returnApiError('您购物车商品优惠活动有变化，请返回刷新购物车');
        }
        $cart_goods = $check_cart_goods_activity['cart_goods'];
        return $cart_goods;
    }

    /**
     * 检查购物车中的商品当前参与的活动是否有变化
     * @param $cart_goods
     * @return array
     */
    private function check_cart_goods_act_change($cart_goods){
        $res = array('has_change'=>false,'cart_goods'=>$cart_goods);
        foreach($cart_goods as $goods){
            if(in_array($goods['giving'],array(1,2,6))){
                continue;
            }
            $activity_list = S('cart_goods_activity_'.$goods['user_id'].'_'.$goods['goods_id']);
            $new_activity_list = array();
            foreach($goods['activity_list'] as $activity){
                $new_activity_list[] = $activity['act_id'];
                $activity_info = S('cart_goods_activity_info_'.$goods['user_id'].'_'.$goods['goods_id'].'_'.$activity['act_id']);

                if($activity_info['act_type']==0 && $activity_info['act_type']!=$activity['act_type']){
                    $cart_goods = $this->delete_cart_favourable_goods($activity['act_id'],$cart_goods,$goods['user_id']);
                    $res['has_change'] = true;
                }elseif($activity_info['act_type']!=$activity['act_type']){
                    $res['has_change'] = true;
                }
                S('cart_goods_activity_info_'.$goods['user_id'].'_'.$goods['goods_id'].'_'.$activity['act_id'],$activity);
            }

            if(!empty($activity_list)){
                $a_dif1 = array_diff($new_activity_list,$activity_list);
                $a_dif2 = array_diff($activity_list,$new_activity_list);

                if(count($a_dif1)>0 || count($a_dif2)>0){
                    $res['has_change'] = true;
                }
            }elseif(empty($activity_list) && !empty($new_activity_list)){
                $res['has_change'] = true;
            }
            S('cart_goods_activity_'.$goods['user_id'].'_'.$goods['goods_id'],$new_activity_list);
        }
        $res['cart_goods'] = $cart_goods;
        return $res;
    }

    /**
     * 获取对应分类的所有子分类
     * @param $cates
     * @return array
     */
    public function get_sub_cate($cates){
        if(!empty($cates)){
            $cid_array=array();
            if(is_array($cates)){
                foreach($cates as $cat_id){
                    //获取当前分类的所有子分类
                    $cat_list = S('category_child_cat_id_by_parentid_'.$cat_id);
                    if(empty($cat_list)){
                        $temp_cate_list = array();
                        $cat_child_list = D('category')->cat_list($cat_id,0,false,0,false);
                        foreach ($cat_child_list as $cate_val){
                            $temp_cate_list[] = $cate_val['cat_id'];
                        }
                        array_push($temp_cate_list,$cat_id);
                        $cat_list = array_unique($temp_cate_list);
                        S('category_child_cat_id_by_parentid_'.$cat_id,$cat_list,3600);
                    }
                    $cid_array = array_merge($cat_list,$cid_array);
                    $cid_array = array_unique($cid_array);
                }
            }else{
                //获取当前分类的所有子分类
                $cid_array = S('category_child_cat_id_by_parentid_'.$cates);
                if(empty($cid_array)){
                    $cat_list = D('category')->cat_list($cates,0,false,0,false);
                    foreach ($cat_list as $cate_val){
                        $cid_array[] = $cate_val['cat_id'];
                    }
                    array_push($cid_array,$cates);
                    $cid_array = array_unique($cid_array);
                    S('category_child_cat_id_by_parentid_'.$cates,$cid_array,3600);
                }
            }

            return $cid_array;
        }else{
            return $cates;
        }

    }
    /**
     * 检查当前购物车商品当前的活动是否存在或者过期
     * @param $cart_goods
     * @param $favourbale_list
     * @return bool
     */
    public function is_exit_activity($cart_goods,$favourbale_list){
        $flag = true;
        $current_activity_list = array();
        foreach ($favourbale_list as $activity){
            $current_activity_list[] = $activity['act_id'];
        }

        foreach($cart_goods as $goods){
            if($goods['act_id']>0 && !in_array($goods['act_id'],$current_activity_list)){
                $flag = false;
                break;
            }
        }

        return $flag;
    }

    public function check_activity_status($act_id){
        $can_redemption=0;
        $need_add_price= 0;
        $favourbale_info = M('avourable_activity')->where(array('act_id'=>$act_id))->find();

        $map = array();
        $map['act_id'] = $act_id;
        $map['giving'] = array('not in',array(1,2));
        $field = "sum(goods_price*goods_number) as favourable_price";
        $cart_info = M('cart')->field($field)->where($map)->find();
        $favourable_goods_total_price = $cart_info['favourable_price'];

        if($favourable_goods_total_price>0 && $favourable_goods_total_price-$favourbale_info['min_amount']>=0){
            $can_redemption=1;
        }else{
            $need_add_price = $favourbale_info['min_amount']-$favourable_goods_total_price;
        }

        $result['act_id'] = $favourbale_info['act_id'];
        $result['can_redemption'] = $can_redemption;
        $result['need_add_price'] = $need_add_price;

        return $result;
    }
    /**
     * 修改购物车商品活动数据
     * @param int $rec_id
     * @param array $data
     */
    public function change_cart_goods_act($rec_id,$data){
        $res = M('cart')->where(array('rec_id'=>$rec_id))->save($data);
        return $res;
    }


    /**
     * 删除购物车中的商品
     * @param unknown $rec_id
     */
    public function remove_cart_goods($rec_id){
        M('cart')->where(array('rec_id'=>$rec_id))->delete();
    }

    public function favourable_list_flow($uid,$wid){
        if(empty($wid)){
            $wid = C('DEFAULT_WID');
        }
        //获取当前用户等级
        $user_rank = D('users')->where(array('user_id'=>$uid))->getField('user_rank');
        if(empty($user_rank)){
            $user_rank = 1;
        }
        $now = gmtime();

        $map = array();

        $map["start_time"] = array('elt',$now);
        $map["end_time"] = array('egt',$now);
        $map["range_of_activity"] = array('NEQ',2);
        $map['act_type'] = array('in',array(FAT_GOODS, FAT_PRICE, FAT_DISCOUNT, FAT_DISCOUNT_LIMIT));
        $map['_string'] = "FIND_IN_SET(".$user_rank.", user_rank)";

        //获取当前用户可参与的活动（除抢购外）
        $favourable_activity_list = M('favourable_activity')->where($map)->order('sort_order desc,act_id desc')->select();

        $goods_sn_arr=array();

        foreach ($favourable_activity_list as $key=>$favourable) {

            $favourable ['start_time'] = local_date(C('time_format'), $favourable ['start_time']);
            $favourable ['end_time'] = local_date(C('time_format'), $favourable ['end_time']);
            $favourable ['formated_min_amount'] = price_format($favourable ['min_amount'], false);
            $favourable ['formated_max_amount'] = price_format($favourable ['max_amount'], false);
            $favourable_gift = unserialize($favourable ['gift']);

            $gift_list = array();
            //获取赠品或换购商品图


            foreach($favourable_gift as $key_gift=>$gift){
                $goods = M('goods_wid_'.$wid)->field('goods_number,is_negative_to_sell,negative_to_sell_start_time,negative_to_sell_end_time,goods_sn,goods_img,practical_num as goods_stock,is_on_sale,is_delete,spec_value,spec_unit')->where(array('goods_id'=>$gift['id']))->find();
                if($goods['is_delete']==0){
                    $goods_sn_arr[]=$goods['goods_sn'];
                    $favourable_gift[$key_gift]['goods_sn'] = $goods['goods_sn'];
                    $favourable_gift[$key_gift]['goods_img'] = img_init($goods['goods_img']);
                    $now=date("Y-m-d H:i:s");

                    if($goods['is_presell']!=0 || $goods['is_negative_to_sell']==1){
                        //检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
                        $is_presell = D('Goodsstorage')->check_whether_presell($goods['goods_id'], $wid,1);
                    }
                    
                    if($is_presell && $goods['is_negative_to_sell']==1 && $goods['negative_to_sell_start_time']<=$now && $goods['negative_to_sell_end_time']>=$now){
                        //负卖
                        $favourable_gift[$key_gift]['goods_stock'] = $goods['goods_number'];
                    }else{
                        $favourable_gift[$key_gift]['goods_stock'] = $goods['goods_stock'];
                    }

                    //                    $goods_detail_info = D('goods')->get_goods_detail_info($gift['id'],$user_rank);
                    $favourable_gift[$key_gift]['goods_price'] = D('goods')->get_vip_price_for_all($gift['id'],$user_rank);
                    $favourable_gift[$key_gift]['spec_value'] = $goods['spec_value'];
                    $favourable_gift[$key_gift]['spec_unit'] = $goods['spec_unit'];
                    $gift_list[] = $favourable_gift[$key_gift];
                }
            }





            $favourable ['gift'] = $gift_list;
            $favourable ['quota'] = unserialize($favourable ['quota']);
            $favourable ['act_tag'] = $this->check_activity_tag($favourable ['act_type'],$favourable ['gift'],$favourable ['act_range'],$favourable ['act_range_ext'],$favourable ['min_amount']);
            $favourable['discount'] = json_decode($favourable['discount'], true);
            $favourable_list [] = $favourable;
        }


        if(in_array($wid,C('K3_Wid'))){
            $kingDee=new KingdeeService();
            $goods_practical_num=$kingDee->getGoodsStockByGoodsSn($wid,$goods_sn_arr);
            $goodsstorage_list_k3=$goods_practical_num['data'];

            foreach($favourable_list as $key=>$favourable){
                foreach($favourable['gift'] as $key_gift=>$gift){
                    isset($goodsstorage_list_k3[$gift["goods_sn"]]) ? $favourable_list[$key]['gift'][$key_gift]['goods_stock'] = $goodsstorage_list_k3[$gift["goods_sn"]] : $favourable_list[$key]['gift'][$key_gift]['goods_stock'] = 0;
                }
            }
        }

        return $favourable_list;

    }
    /**
     * 操作购物车商品
     * @param int $uid 用户ID
     * @param int $goods_id  商品ID
     * @param int $num 商品数量
     * @param string $spec 商品属性
     * @param int $wid 仓库ID
     * @param string $operate 操作类型
     */

    function __construct() {

    }

    public function change_cart_num($uid, $goods_id, $num,$spec='',$wid=0,$operate='add',$act_id=0,$act_type,$reset_giving){

        if(!isset($goods_id) || empty($goods_id)){
            return array("status"=>0,"msg"=>"商品ID错误");
        }

        if(empty($num)){
            $num=1;
        }

        //检验商品属性
        if($spec){
            $spec=explode(',', $spec);
        }
        $is_spec_true=$this->check_spec($goods_id,$spec);
        if(!$is_spec_true['status']){
            return $is_spec_true;
        }

        // 更新：如果是一步购物，先清空购物车
        if (C('one_step_buy') == '1') {
            D('NewCart')->clear_cart($uid);
        }

        $cart_goods = $this->is_exists_record( $uid, $goods_id ,$act_id,$act_type);



        if($cart_goods){
            //当前购物车商品数量
            $current_num = $cart_goods['goods_number'];
        }else{
            $current_num =0;
        }
        //获取商品起购数量
        $min_buy_num = $this->min_buy_num($goods_id);




        //不是限购商口加减删处理
        if($operate == "add"){
            $do_num = $current_num+$num;

            if($do_num<$min_buy_num){
                $do_num = $min_buy_num;
            }
        }elseif($operate == "dec"){
            $do_num = $current_num-$num;
            if($do_num<$min_buy_num){
                $do_num = 0;
            }
        }elseif ($operate == 'del'){
            $do_num = 0;
        }elseif ($operate == 'equ'){
            $do_num = $num;
        }



        // 更新：添加到购物车
        $re_msg=$this->change_cart($uid,$goods_id, $do_num, $spec, $wid,$act_id,$act_type,$operate);
        if (!$re_msg['status']) {
            return $re_msg;
        }

        return array('status'=>1);
    }


    /**
     * 增减购物车
     * @param $uid
     * @param $goods_id
     * @param int $num
     * @param array $spec
     * @param int $wid
     * @param int $act_id
     * @param $act_type
     * @param $operate
     * @param int $_parent_id
     * @return array
     */
    public function change_cart($uid,$goods_id,$num=1,$spec = array(),$wid=0,$act_id=0,$act_type,$operate,$_parent_id=0){
        global $is_cashier;
        global $cashier_id;
        $Model=new Model();
        //获取会员等级
        $user_rank = D('users')->where(array('user_id'=>$uid))->getField('user_rank');
        $user_rank_temp=$user_rank;

        /* 取得商品信息 */
        if(empty($_SESSION['discount']) || $_SESSION['discount']=='0.00'){
            $user_rank = D('Users')->get_user_rank($uid);
            $_SESSION['discount']=$user_rank['discount'];
        }

        //获取商品会员价格
        $goods=$this->get_rank_goods_info($goods_id, $user_rank,$wid);
        if (empty($goods)) {
            return array('status'=>0,'msg'=>'商品不存在或已下架');
        }

        if($act_id==0){
            $act_id=$this->get_goods_activity($uid,$wid, $goods);
        }
        /* 是否正在销售 */
        if ($goods['is_on_sale'] == 0 && $operate=='add' &&  $act_type!='is_exchange' && $goods['offline_can_buy'] == 0) {
            return array('status'=>0,'msg'=>'商品已下架');
        }

        /* 不是配件时检查是否允许单独销售 */
        if (empty($parent) && $goods['is_alone_sale'] == 0) {
            return array('status'=>0,'msg'=>'该商品不能单独销售');
        }


        /* 如果商品有规格则取规格商品信息 配件除外 */
        $sql = "SELECT * FROM " . C('DB_PREFIX') . "products WHERE goods_id = '$goods_id' LIMIT 0, 1";
        $prod = $Model->query($sql);
        if (D('Goods')->is_spec($spec) && !empty($prod)) {
            $product_info = D('Goods')->get_products_info($goods_id, $spec);
        }

        if (empty($product_info)) {
            $product_info = array('product_number' => '', 'product_id' => 0);
        }


        // 检查：库存：系统启用了库存，检查输入的商品数量是否有效
        if (C('use_storage') == 1 && $operate=='add') {

            if($act_type=='is_exchange'){
                $check_num=M("cart")->where(array('goods_id'=>$goods_id,'giving'=>array('in','0,4'),'user_id'=>$uid,'is_cashier'=>$is_cashier,'cashier_id'=>$cashier_id))->getField("goods_number");
                $check_num+=$num;
            }else{
                $check_num=M("cart")->where(array('goods_id'=>$goods_id,'giving'=>array('in','1,2'),'user_id'=>$uid,'is_cashier'=>$is_cashier,'cashier_id'=>$cashier_id))->getField("goods_number");
                $check_num+=$num;
            }

            $is_valid_true=$this->check_num_valid($goods_id,$wid,$check_num);
            if(!$is_valid_true['status']){
                return $is_valid_true;
            }
        }


        /* 计算商品的促销价格 */
        $spec_price = D('Goods')->spec_price($spec);
        $goods_price = D('Goods')->get_final_price($goods_id, $num, true, $spec, $uid);

        $goods['market_price'] += $spec_price;
        $goods_attr = D('Goods')->get_goods_attr_info($spec);
        $goods_attr_id = join(',', $spec);

        /* 初始化要插入购物车的基本件数据 */
        $parent = array(
            'user_id' => $uid,
            'session_id' => SESS_ID,
            'goods_id' => $goods_id,
            'goods_sn' => addslashes($goods['goods_sn']),
            'product_id' => $product_info['product_id'],
            'goods_name' => addslashes($goods['goods_name']),
            'market_price' => $goods['market_price'],
            'goods_attr' => addslashes($goods_attr),
            //'goods_attr_id' => $goods_attr_id,
            'is_real' => $goods['is_real'],
            'extension_code' => $goods['extension_code'],
            'is_gift' => 0,
            'is_quota' => 0,
            'is_shipping' => $goods['is_shipping'],
            'is_presell' => $goods['is_presell'],
            'rec_type' => CART_GENERAL_GOODS,

        );
        if(!empty($goods_attr_id)){
            $parent['goods_attr_id']=$goods_attr_id;
        }

        //分类限购检查
        $res = D('Goods')->check_cat_max_buy_number($parent,$goods_price,$uid,$num);

        /* 如果该配件在添加为基本件的配件时，所设置的“配件价格”比原价低，即此配件在价格上提供了优惠， */
        /* 则按照该配件的优惠价格卖，但是每一个基本件只能购买一个优惠价格的“该配件”，多买的“该配件”不享 */
        /* 受此优惠 */
        $basic_list = array();
        $sql = "SELECT parent_id, goods_id, goods_price " ."FROM " . C('DB_PREFIX') ."group_goods WHERE goods_id = '$goods_id'" ." AND goods_price < '$goods_price'" ." AND parent_id = '$_parent_id'" ." ORDER BY goods_price";
        $res = $Model->query($sql);
        foreach ($res as $key=>$row) {
            $basic_list[$row['parent_id']] = $row['goods_price'];
        }
        /* 取得购物车中该商品每个基本件的数量 */
        $basic_count_list = array();

        if ($basic_list) {
            $sql = "SELECT goods_id, SUM(goods_number) AS count " .
                "FROM " . C('DB_PREFIX') .
                "cart WHERE user_id = '" . $uid . "'" .
                " AND parent_id = 0" .
                " AND extension_code <> 'package_buy' " .
                " AND goods_id " . db_create_in(array_keys($basic_list)) .
                " GROUP BY goods_id";
            $res = $Model->query($sql);
            foreach ($res as $key=>$row) {
                $basic_count_list[$row['goods_id']] = $row['count'];
            }
        }

        /* 取得购物车中该商品每个基本件已有该商品配件数量，计算出每个基本件还能有几个该商品配件 */
        /* 一个基本件对应一个该商品配件 */
        if ($basic_count_list) {
            $sql = "SELECT parent_id, SUM(goods_number) AS count " .
                "FROM " .C('DB_PREFIX') .
                "cart WHERE user_id = '" . $uid . "'" .
                " AND goods_id = '$goods_id'" .
                " AND extension_code <> 'package_buy' " .
                " AND parent_id " . db_create_in(array_keys($basic_count_list)) .
                " GROUP BY parent_id";
            $res = $Model->query($sql);
            foreach ($res as $key=>$row) {
                $basic_count_list[$row['parent_id']] -= $row['count'];
            }
        }

        /* 循环插入配件 如果是配件则用其添加数量依次为购物车中所有属于其的基本件添加足够数量的该配件 */
        foreach ($basic_list as $parent_id => $fitting_price) {
            /* 如果已全部插入，退出 */
            if ($num <= 0) {
                break;
            }

            /* 如果该基本件不再购物车中，执行下一个 */
            if (!isset($basic_count_list[$parent_id])) {
                continue;
            }

            /* 如果该基本件的配件数量已满，执行下一个基本件 */
            if ($basic_count_list[$parent_id] <= 0) {
                continue;
            }

            /* 作为该基本件的配件插入 */
            $parent['goods_price'] = max($fitting_price, 0) + $spec_price; //允许该配件优惠价格为0
            $parent['goods_number'] = min($num, $basic_count_list[$parent_id]);
            $parent['parent_id'] = $parent_id;
            $parent['is_cashier'] = $is_cashier;
            $parent['cashier_id'] = $cashier_id;

            /* 添加 */
            M('cart')->add($parent);
            /* 改变数量 */
            $num -= $parent['goods_number'];


        }



        /* 检查该商品是否已经存在在购物车中 */
        $row = $this->get_goods_info($uid, $goods_id, $spec,$act_type,$act_id);
        $change_type = '';
        /* 如果数量不为0，作为基本件插入 */
        if ($num > 0) {

            if ($row) { //如果购物车已经有此物品，则更新
                $cartdata=array();
                if($row['act_id'] && in_array($row['giving'],array('0','4'))){
                    //添加活动普通商品
                    //$re_act=$this->check_activity_valid($user_rank_temp, $act_id, $goods,$act_type);
                    $act_goods_amount=$this->get_act_cart_goods_total($uid, $row['act_id'],$goods_id);
                    $act_goods_amount+=$goods_price*$num;
                    $act_info=$this->get_act_info($row['act_id'],$user_rank_temp);
                    $gift=unserialize($act_info['gift']);
                    foreach($gift as $item){
                        $goods_id_list[]=$item['id'];
                        $goods_price_list[]=$item['price'];
                        $goods_list[$item['id']]=$item['price'];
                    }

//                	促销价范围
                    $promoteService = new PromoteService();
                    $goodsNumber = $num;
                    $is_promote = $promoteService->isPromote($uid, $goods_id, $goodsNumber);

                    if ($is_promote === -1 || $is_promote === -2 || $is_promote === -3 || $is_promote === -4) {
                        return array(
                            'status' => 0,
                            'msg' => $promoteService->getErrorMessage(),
                        );
                    }



                    if($act_info['act_range']==3 && is_numeric($act_info['act_range_ext']) && count($gift)==1 && $act_info['act_type']==0 && $act_info['min_amount']==0 && $goods_list[$gift[0]['id']]==0 && $row['is_check']=='1'){

                        //买一赠一
                        if($num>$act_info['act_type_ext'] && floatval($act_info['act_type_ext'])!=0){
                            $change_num=$act_info['act_type_ext'];
                        }else{
                            $change_num=$num;
                        }
                        $change_num1=$change_num;
                        if($gift[0]['id']==$goods_id){
                            $change_num1=$change_num*2;
                        }

                        $is_valid_true=$this->check_num_valid($gift[0]['id'],$wid,$change_num1);
                        if($is_valid_true['status']){

                            $re_msg=$this->change_cart($uid,$gift[0]['id'],$change_num,array(),$wid,$row['act_id'],'is_exchange',0);
                            if(!$re_msg['status']){
                                return $re_msg;
                            }
                        }
                    }else if(count($gift)==1 && $act_info['act_type']==0 && $goods_list[$gift[0]['id']]==0 && $row['is_check']=='1'){
                        $change_num1=1;
                        if($gift[0]['id']==$goods_id){
                            $change_num1=$num+1;
                        }

                        $is_valid_true=$this->check_num_valid($gift[0]['id'],$wid,$change_num1);
                        if($is_valid_true['status']){
                            $re_msg=$this->change_cart($uid,$gift[0]['id'],1,array(),$wid,$row['act_id'],'is_exchange',0);
                            if(!$re_msg['status']){
                                return $re_msg;
                            }
                        }
                    }else if(floatval($act_info['min_amount'])>floatval($act_goods_amount)){
                        //不满足优惠条件，则清除换购和赠品
                        $this->clean_act_giving_goods($uid,$act_info['act_id']);
                    }

                    $cartdata=array(
                        'goods_number'=>$num,
                        'goods_price'=>$goods_price
                    );
                }else if($row['act_id'] && in_array($row['giving'],array('3'))){
                    //限购活动商品
                    $act_info=$this->get_act_info($row['act_id'],$user_rank_temp);
                    if(!$act_info || $act_info['act_type']<>3 || !($act_info['act_range']==0 || $act_info['act_range']==1 && in_array($goods['cat_id'],explode(",",$act_info['act_range_ext'])) || $act_info['act_range']==2 && in_array($goods['brand_id'],explode(",",$act_info['act_range_ext'])) || $act_info['act_range']==3 && in_array($goods['goods_id'],explode(",",$act_info['act_range_ext'])))){
                        return array('status'=>0,'msg'=>'该商品不符合限购活动或已过期');
                        $this->clean_act_quota_goods($uid,$act_info['act_id']);
                    }
                    $quota=unserialize($act_info['quota']);
                    $quota_i=array();
                    if($act_info['act_range']==1){
                        foreach($quota as $item){
                            if($item['id']==$goods['cat_id']){
                                $quota_i['count']=$item['count'];
                                $quota_i['price']=$item['price'];
                                break;
                            }
                        }
                    }else if($act_info['act_range']==2){
                        foreach($quota as $item){
                            if($item['id']==$goods['brand_id']){
                                $quota_i['count']=$item['count'];
                                $quota_i['price']=$item['price'];
                                break;
                            }
                        }

                    }else if($act_info['act_range']==3){
                        foreach($quota as $item){
                            if($item['id']==$goods['goods_id']){
                                $quota_i['count']=$item['count'];
                                $quota_i['price']=$item['price'];
                                break;
                            }
                        }
                    }

                    /* 检查是否已参与过该活动 */
                    $quota_favourable = $this->activity_favourable_quota($row['act_id'],'',$uid);
                    if ($quota_favourable && $quota_favourable['num'] > 0) {
                        return array('status'=>0,'msg'=>"此活动您已参与过");
                    }

                    if($quota_i['count']>0 && $quota_i['count']<$num){
                        return array('status'=>0,'msg'=>"此活动限购" . $quota_i['count'] . "份，超出限购数量!");
                    }

                    //活动数量限制
                    $this_act_num=$this->get_quota_goods_num($uid, $act_id,$goods_id);

                    if($act_info['act_type_ext']>0 && $act_info['act_type_ext']<($this_act_num+$num)){
                        return array('status'=>0,'msg'=>"此活动限购" . $quota_i['count'] . "份，超出限购数量!");
                    }

                    $cartdata=array(
                        'goods_number'=>$num,
                        'goods_price'=>$quota_i['price']
                    );

                }else if($row['act_id'] && in_array($row['giving'],array('2','1'))){
                    //添加活动换购商品或赠品
                    $act_goods_amount=$this->get_act_cart_goods_total($uid, $row['act_id'],$goods_id);
                    $act_info=$this->get_act_info($row['act_id'],$user_rank_temp);
                    $gift=unserialize($act_info['gift']);
                    $giving_num=$this->get_giving_goods_num($uid, $row['act_id'],$goods_id);
                    foreach($gift as $item){
                        $goods_id_list[]=$item['id'];
                        $goods_price_list[]=$item['price'];
                        $goods_list[$item['id']]=$item['price'];
                    }
                    if(!in_array($goods_id,$goods_id_list)){
                        return array('status'=>0,'msg'=>'该商品不符合该活动或已过期');
                    }


                    if(!($act_info['act_range']==3 && is_numeric($act_info['act_range_ext']) && count($gift)==1 && $act_info['act_type']==0 && $act_info['min_amount']==0 && $goods_list[$goods_id]==0)){
                        if(floatval($act_goods_amount)<floatval($act_info['min_amount'])){
                            $this->clean_act_giving_goods($uid,$act_info['act_id']);
                            //return array('status'=>0,'msg'=>'不满足该活动条件');
                        }
                        if($giving_num+$num>$act_info['act_type_ext'] && floatval($act_info['act_type_ext'])!=0){
                            //换购或赠品最大数量不能超过设置数
                            return array('status'=>0,'msg'=>'换购或赠品超过最大数量');
                        }
                    }

                    $cartdata=array(
                        'goods_number'=>$num,
                        'goods_price'=>$goods_list[$goods_id]
                    );

                }
                else if (in_array($row['giving'], array('4'))) {
                    if ($num < $row['goods_number']) {
                        $cartdata = array(
                            'goods_number' => $num,
                            'goods_price' => $goods_price,
                        );
                    } else {
                        //                		促销价范围
                        $promoteService = new PromoteService();
                        $goodsNumber = $num;
                        $is_promote = $promoteService->isPromote($uid, $goods_id, $goodsNumber);

                        if ($is_promote === true) {
                            $cartdata = array(
                                'act_id' => $act_id,
                                'goods_number' => $num,
                                'goods_price' => $goods_price,
                            );
                        }
                        elseif ($is_promote === -1 || $is_promote === -2 || $is_promote === -3) {
                            return array(
                                'status' => 0,
                                'msg' => $promoteService->getErrorMessage(),
                            );
                        }
                    }

                } //				秒杀价处理
                else if (in_array($row['giving'], array('5'))) {

                    if ($operate == 'dec') {
                        $cartdata = array(
                            'goods_number' => $row['goods_number'] - $num,
                            'goods_price' => $goods_price
                        );
                    } else if ($operate == 'add') {
                        $buyNowGoodsService = new BuyNowGoodsService($uid, $wid);
                        $goodsNumber = $num;
                        $is_buy_now = $buyNowGoodsService->isBuyNowGoods($goods_id, $goodsNumber);
                        if ($is_buy_now === true) {
                            $cartdata = array(
                                'act_id' => $act_id,
                                'goods_number' => $goodsNumber,
                                'goods_price' => $goods_price
                            );
                        } else {
                            return array(
                                'status' => 0,
                                'msg' => $buyNowGoodsService->getErrorMessage(),
                            );
                        }
                    }

                }
                //				普通商品
                else {
                    $act_id = $this->get_goods_activity($uid,$wid,$goods);
                    $cartdata = array(
                        'act_id' => $act_id,
                        'goods_number' => $num,
                        'goods_price' => $goods_price
                    );
                }

                $rec_id = $row['rec_id'];

                $where = array('rec_id'=>$rec_id,'user_id'=>$uid,'goods_id'=>$goods_id);
                M('Cart')->where($where)->save($cartdata);
                $change_type='add';

            } else { //购物车没有此物品，则插入
                if($act_id && empty($act_type)){
                    $act_info = $this->get_act_info($act_id,$user_rank_temp);
                    if($act_info['act_type']=='3'){
                        //$act_type='is_quota';
                    }
                }
                $parent['goods_price'] = max($goods_price, 0);
                $parent['goods_number'] = $num;
                $parent['parent_id'] = 0;
                $parent['is_cashier'] = $is_cashier;
                $parent['cashier_id'] = $cashier_id;



                if($act_id && $act_type=='is_exchange'){

                    //添加活动换购商品或赠品
                    $act_goods_amount=$this->get_act_cart_goods_total($uid, $act_id,$goods_id);
                    $act_info=$this->get_act_info($act_id,$user_rank_temp);
                    $gift=unserialize($act_info['gift']);
                    $giving_num=$this->get_giving_goods_num($uid, $act_id,$goods_id);

                    foreach($gift as $item){
                        $goods_id_list[]=$item['id'];
                        $goods_price_list[]=$item['price'];
                        $goods_list[$item['id']]=$item['price'];
                    }
                    if(!in_array($goods_id, $goods_id_list) || $act_info['act_type']!='0'){
                        return array('status'=>0,'msg'=>'该商品不符合该活动或已过期');
                    }

                    //换购或赠品最大数量不能超过设置数
                    if($giving_num+$num>$act_info['act_type_ext'] && floatval($act_info['act_type_ext'])!=0){
                        $num=$act_info['act_type_ext'];
                        return array('status'=>0,'msg'=>'数量不能大于'.$act_info['act_type_ext']);
                    }

                    if(!($act_info['act_range']==3 && is_numeric($act_info['act_range_ext']) && count($gift)==1 && $act_info['min_amount']==0) && floatval($act_goods_amount)<floatval($act_info['min_amount'])){
                        //return array('status'=>0,'msg'=>'不满足该活动条件');
                    }

                    $goods_price=$goods_list[$goods_id];
                    if(floatval($goods_price)){
                        $parent['giving'] = 2;
                    }else{
                        $parent['giving'] = 1;
                    }

                    $parent['goods_price'] = $goods_price;
                    $parent['act_id'] = $act_info['act_id'];
                    $parent['is_gift'] = $act_info['act_id'];


                }else if($act_id && $act_type=='is_quota'){

                    //添加限购活动商品
                    $act_info=$this->get_act_info($act_id,$user_rank_temp);

                    if(!$act_info || $act_info['act_type']<>3 || !($act_info['act_range']==0 || $act_info['act_range']==1 && in_array($goods['cat_id'],explode(",",$act_info['act_range_ext'])) || $act_info['act_range']==2 && in_array($goods['brand_id'],explode(",",$act_info['act_range_ext'])) || $act_info['act_range']==3 && in_array($goods['goods_id'],explode(",",$act_info['act_range_ext'])))){
                        return array('status'=>0,'msg'=>'该商品不符合限购活动或已过期');
                    }
                    $quota=unserialize($act_info['quota']);
                    $quota_i=array();
                    if($act_info['act_range']==1){
                        foreach($quota as $item){
                            if($item['id']==$goods['cat_id']){
                                $quota_i['count']=$item['count'];
                                $quota_i['price']=$item['price'];
                                break;
                            }
                        }
                    }else if($act_info['act_range']==2){
                        foreach($quota as $item){
                            if($item['id']==$goods['brand_id']){
                                $quota_i['count']=$item['count'];
                                $quota_i['price']=$item['price'];
                                break;
                            }
                        }

                    }else if($act_info['act_range']==3){
                        foreach($quota as $item){
                            if($item['id']==$goods['goods_id']){
                                $quota_i['count']=$item['count'];
                                $quota_i['price']=$item['price'];
                                break;
                            }
                        }
                    }

                    /* 检查是否已参与过该活动 */
                    $quota_favourable = $this->activity_favourable_quota($act_id,'',$uid);
                    if ($quota_favourable && $quota_favourable['num'] > 0) {
                        return array('status'=>0,'msg'=>"此活动您已参与过");
                    }

                    if($quota_i['count']>0 && $quota_i['count']<$num){
                        return array('status'=>0,'msg'=>"此活动限购" . $quota_i['count'] . "份，超出限购数量!");
                    }

                    //活动数量限制
                    $this_act_num=$this->get_quota_goods_num($uid, $act_id,$goods_id);

                    if($act_info['act_type_ext']>0 && $act_info['act_type_ext']<($this_act_num+$num)){
                        return array('status'=>0,'msg'=>"此活动限购" . $quota_i['count'] . "份，超出限购数量!");
                    }

                    $parent['giving'] = 3;
                    $parent['act_id'] = $act_id;
                    $parent['goods_price'] = $quota_i['price'];

                }
                else if ($act_type=='is_promote'){
                    //					促销价范围处理
                    $promoteService = new PromoteService();
                    $is_promote = $promoteService->isPromote($uid, $goods['goods_id'], $num);

                    if ($is_promote === true) {
                        $parent['act_id'] = $act_id;
                        $parent['giving'] = 4;
                    }
                    elseif ($is_promote === -1 || $is_promote === -2 || $is_promote === -3){
                        return array(
                            'status'	=>	0,
                            'msg'		=>	$promoteService->getErrorMessage(),
                        );
                    }
                }
                //				秒杀商品处理
                else if ($act_type=='is_buynow'){
                    $buyNowGoodsService = new BuyNowGoodsService($uid, $wid);
                    $is_buy_now = $buyNowGoodsService->isBuyNowGoods($goods['goods_id'], $num);

                    if ($is_buy_now === true) {
                        $parent['giving'] = 5;
                    }
                    else{
                        return array(
                            'status'	=>	0,
                            'msg'		=>	$buyNowGoodsService->getErrorMessage(),
                        );
                    }
                }
                else{
                    $parent['act_id'] = $act_id;

                    //设置第一次加入购物车的价格
                    S('goods_add_cart_price_'.$uid."_".$goods_id,$parent['goods_price']);
                }



                $rec_id = M('Cart')->add($parent);



                $change_type = 'add';
                if($rec_id && $act_id && $act_type!='is_exchange'){
                    //添加活动普通商品
                    //$re_act=$this->check_activity_valid($user_rank_temp, $act_id, $goods,$act_type);
                    $act_goods_amount=$this->get_act_cart_goods_total($uid, $act_id,$goods_id);
                    $act_goods_amount+=$goods_price*$num;
                    $act_info=$this->get_act_info($act_id,$user_rank_temp);
                    $gift=unserialize($act_info['gift']);
                    foreach($gift as $item){
                        $goods_id_list[]=$item['id'];
                        $goods_price_list[]=$item['price'];
                        $goods_list[$item['id']]=$item['price'];
                    }

                    if($act_info['act_range']==3 && is_numeric($act_info['act_range_ext']) && count($gift)==1 && $act_info['act_type']==0 && $act_info['min_amount']==0 && $goods_list[$gift[0]['id']]==0){
                        //买一赠一
                        if($num>$act_info['act_type_ext'] && floatval($act_info['act_type_ext'])!=0){
                            $change_num=$act_info['act_type_ext'];
                        }else{
                            $change_num=$num;
                        }
                        $change_num1=$change_num;
                        if($gift[0]['id']==$goods_id){
                            $change_num1=$change_num*2;
                        }

                        $is_valid_true=$this->check_num_valid($gift[0]['id'],$wid,$change_num1);
                        if($is_valid_true['status']){
                            $re_msg=$this->change_cart($uid,$gift[0]['id'],$change_num,'',$wid,$act_id,'is_exchange');
                            if(!$re_msg['status']){
                                return $re_msg;
                            }
                        }


                    }else if(count($gift)==1 && $goods_list[$goods_id]==0 && $act_info['act_type']==0 && floatval($act_info['min_amount'])<floatval($act_goods_amount) && $goods_list[$gift[0]['id']]==0){
                        $change_num1=1;
                        if($gift[0]['id']==$goods_id){
                            $change_num1=$num+1;
                        }
                        //单一赠品，符合条件自动添加赠品
                        $is_valid_true=$this->check_num_valid($gift[0]['id'],$wid,$change_num1);
                        if($is_valid_true['status']){
                            $re_msg=$this->change_cart($uid,$gift[0]['id'],1,array(),$wid,$act_id,'is_exchange',0);
                            if(!$re_msg['status']){
                                return $re_msg;
                            }
                        }
                    }

                }

            }
        }else{
            $act_goods_amount=$this->get_act_cart_goods_total($uid, $act_id,$goods_id);

            $act_info=$this->get_act_info($act_id,$user_rank_temp);
            if(floatval($act_info['min_amount'])>floatval($act_goods_amount) || floatval($act_goods_amount)==0){
                //不满足优惠条件，则清除换购和赠品
                $this->clean_act_giving_goods($uid,$act_info['act_id']);
            }

            $this->remove_shopping_cart_goods($uid, $row['rec_id']);
        }

        return array('status'=>1,'goods_price'=>$goods_price,'rec_id'=>$rec_id,'change_type'=>$change_type);
    }

    /**
     * 插入活动id
     * Created by Jerry
     * @param $cart_id
     * @param $act_id
     * @return bool
     */
    protected function update_cart_for_act_id($cart_id, $act_id)
    {
        $where = array(
            'rec_id'    =>  $cart_id,
        );

        $rs = $this->where($where)->setField('act_id', $act_id);
        return $rs;
    }

    /**
     * 限购活动中的参与信息
     */
    public function activity_favourable_quota($act_id, $goods_id = null,$uid) {
        $sql = "SELECT act_id, COUNT(*) AS num " . "FROM " . C('DB_PREFIX') . "activity_quota  WHERE user_id = " . $uid . " AND act_id='$act_id'" . " GROUP BY act_id";
        if ($goods_id) {
            $sql = "SELECT act_id, COUNT(*) AS num " . "FROM " . C('DB_PREFIX') . "activity_quota  WHERE user_id = " . $uid . " AND act_id='$act_id' AND goods_id=" . $goods_id . " GROUP BY act_id";
        }
        $model = new  Model();
        $res =$model->query($sql);
        return current($res);
    }

    /**
     * 购物车中的限购产品
     */
    public function cart_favourable_quota($act_id, $goods_id = null,$uid='') {
        $map = array();
        $map['rec_type'] = CART_GENERAL_GOODS;
        $map['is_quota'] = $act_id;
        if($goods_id){
            $map['goods_id'] = $goods_id;
        }

        $map['user_id']  = $uid;
        $res = $this->field("is_quota, SUM(goods_number) AS num")->where($map)->group('is_quota')->find();
        return $res;
    }

    public function check_act_giving_vaild_exits($uid,$goods_id){
        //
    }

    public function clean_act_quota_goods($uid,$act_id){
        global $is_cashier;
        global $cashier_id;
        M("cart")->where(array('user_id'=>$uid,'act_id'=>$act_id,giving=>array('in','3'),'is_cashier'=>$is_cashier,'cashier_id'=>$cashier_id))->delete();
    }

    public function clean_act_giving_goods($uid,$act_id){
        global $is_cashier;
        global $cashier_id;
        M("cart")->where(array('user_id'=>$uid,'act_id'=>$act_id,giving=>array('in','1,2'),'is_cashier'=>$is_cashier,'cashier_id'=>$cashier_id))->delete();
    }

    /**
     * 获取参考活动商品的总价格
     * @param int $uid 用户ID
     * @param int $act_id 活动ID
     */
    public function get_act_cart_goods_total($uid,$act_id,$goods_id=0){
        global $is_cashier;
        global $cashier_id;
        $Model=new Model();
        $sql = 'SELECT SUM(goods_price * goods_number) AS amount  FROM ' . C('DB_PREFIX') . 'cart ' ." WHERE user_id = '" . $uid . "' AND act_id=$act_id AND giving in(0,4) AND rec_type = '".CART_GENERAL_GOODS ."' and  goods_id<>'".$goods_id."' and is_cashier='".$is_cashier."' and cashier_id='".$cashier_id."' and is_check='1'";
        $row = $Model->query($sql);
        $act_amount=$row[0]['amount'];
        return $act_amount;
    }

    /**
     * 获取优惠活动信息
     * @param int $act_id 活动ID
     * @return array
     */
    public function get_act_info($act_id,$user_rank){
        if(empty($user_rank)){
            $user_rank=1;
        }
        $Model=new Model();
        $sql = 'SELECT start_time,end_time,act_name,act_id,act_range,act_range_ext,act_type,act_type_ext,min_amount,max_amount,gift,quota FROM ' . C('DB_PREFIX') . 'favourable_activity ' ." WHERE start_time<=".gmtime()." and end_time>".gmtime()." and FIND_IN_SET($user_rank,user_rank) and act_id = '" . $act_id . "' order by sort_order asc";
        $row = $Model->query($sql);
        if($row[0]){
            return $row[0];
        }else{
            return false;
        }
    }

    /**
     * 获取用户活动的换购或赠品数量
     * @param int $act_id 活动ID
     */
    public function get_giving_goods_num($uid,$act_id,$goods_id=0){
        global $is_cashier;
        global $cashier_id;
        $Model=new Model();
        $sql = 'SELECT count(*) AS act_count  FROM ' . C('DB_PREFIX') . 'cart ' ." WHERE user_id = '" . $uid . "' AND act_id=$act_id AND giving in('1','2') and goods_id<>$goods_id and is_cashier='".$is_cashier."' and cashier_id='".$cashier_id."'";
        $row = $Model->query($sql);
        return $row[0]['act_count'];
    }

    /**
     * 获取该限购商品数量
     * @param int $act_id 活动ID
     */
    public function get_quota_goods_num($uid,$act_id,$goods_id=0){
        global $is_cashier;
        global $cashier_id;
        $Model=new Model();
        $sql = 'SELECT SUM(goods_number) AS act_number  FROM ' . C('DB_PREFIX') . 'cart ' ." WHERE user_id = '" . $uid . "' AND act_id=$act_id AND giving in('3') and goods_id<>$goods_id and is_cashier='".$is_cashier."' and cashier_id='".$cashier_id."'";
        $row = $Model->query($sql);
        return $row[0]['act_number'];
    }



    /**
     *
     * @param int $user_rank 会员等级ID
     * @param int $act_id 活动ID
     * @param array $goods 商品信息
     * @param string $act_type 活动类型
     */
    public function check_activity_valid($user_rank,$act_id,$goods,$act_type=''){
        $Model=new Model();
        if($act_type=='is_exchange'){
            $sql="select gift,act_type_ext from " . C('DB_PREFIX') . "favourable_activity where start_time<=".gmtime()." and end_time>".gmtime()." and FIND_IN_SET($user_rank,user_rank) and act_type=0 and act_id=$act_id";
            $result = $Model->query($sql);
            if($result[0]){
                foreach(unserialize($result[0]['gift']) as $item){
                    if($item['id']==$goods['goods_id']){
                        return true;
                    }
                }
                return false;

            }else{
                return false;
            }
        }else{
            $sql="select act_id from " . C('DB_PREFIX') . "favourable_activity where start_time<=".gmtime()." and end_time>".gmtime()." and FIND_IN_SET($user_rank,user_rank) and (act_range=0 or act_range=1 and act_range_ext=".$goods['cat_id']." or act_range=2 and act_range_ext=".$goods['brand_id']." or act_range=3 and act_range_ext=".$goods['goods_id'].") and act_id=$act_id";
            $result = $Model->query($sql);
            if($result[0]){
                return true;
            }else{
                return false;
            }
        }
    }

    /**
     * 获取优惠活动信息
     * @param int $act_id 活动ID
     */
    public function get_activity_info($act_id,$goods_id){
        $Model=new Model();
        $sql="select gift,act_type_ext from " . C('DB_PREFIX') . "favourable_activity where start_time<=".gmtime()." and end_time>".gmtime()." and act_type=0 and act_id=$act_id";
        $result = $Model->query($sql);
        if($result[0]){
            $goods_act=array();
            $goods_act['max_num']=$result[0]['act_type_ext'];
            foreach(unserialize($result[0]['gift']) as $item){
                if($item['id']==$goods_id){
                    $goods_act['act_price']=$item['price'];
                    break;
                }
            }
            return $goods_act;

        }else{
            return 0;
        }

    }

    /**
     * 获取符合商品的优惠活动
     * @param $uid
     * @param $wid
     * @param $goods
     * @return int
     */
    public function get_goods_activity($uid,$wid,$goods){
        $act_id = 0;
        $current_activity_list = $this->favourable_list_flow($uid,$wid);

        foreach ($current_activity_list as $key=>$f_avl){
            $act_range_ext = explode(',', $f_avl['act_range_ext']);
            //如果优惠范围为分类且设置包含子分类，则获取当前设置分类的所有子分类
            if($f_avl['act_range'] == 1 && $f_avl['is_include_subcategory'] == 1){
                $act_range_ext = $this->get_sub_cate($act_range_ext);
            }
            if ($f_avl['act_range'] == 0 || ($f_avl['act_range'] == 1 && in_array($goods['cat_id'], $act_range_ext)) || ($f_avl['act_range'] == 2 && in_array($goods['brand_id'], $act_range_ext)) || ($f_avl['act_range'] == 3 && in_array($goods['goods_id'], $act_range_ext))) {
                $act_id = $f_avl['act_id'];
                break;
            }
        }
        return $act_id;
        //        $Model=new Model();
        //        $sql="select act_id from " . C('DB_PREFIX') . "favourable_activity where start_time<=".gmtime()." and end_time>".gmtime()." and FIND_IN_SET($user_rank,user_rank) and (act_range=0 or act_range=1 and FIND_IN_SET(".$goods['cat_id'].",act_range_ext) or act_range=2 and FIND_IN_SET(".$goods['brand_id'].",act_range_ext) or act_range=3 and FIND_IN_SET(".$goods['goods_id'].",act_range_ext)) and act_type in(0,1,2,3) order by sort_order asc limit 1";
        //        $result = $Model->query($sql);
        //        if($result[0]){
        //            return $result[0]['act_id'];
        //        }

        /**
         * 第二件半价
         */
        //        $favourableModel = D('FavourableActivity');
        //        $favourableData = $favourableModel->get_is_discount(0, $goods['goods_id'], $user_rank);
        //
        //        if (!empty($favourableData)) {
        //            return $favourableData['act_id'];
        //        }

        //        return 0;

    }



    /**
     * 获取商品会员等级价格
     * @param int $goods_id 商品ID
     * @param int $user_rank 会员等级ID
     * @param int $wid
     */
    public function get_rank_goods_info($goods_id,$user_rank,$wid){
        if(empty($user_rank)){
            $user_rank['discount']=1;
            $user_rank['user_rank']=1;
        }
        $Model=new Model();
        $sql = "SELECT g.offline_can_buy,g.cat_id,g.brand_id,g.goods_id,g.goods_name, g.goods_sn, g.is_on_sale, g.is_real,
         g.market_price, g.shop_price AS org_price, g.promote_price, g.promote_start_date,g.promote_end_date, 
         g.goods_weight, g.integral, g.extension_code,g.goods_number, g.is_alone_sale, g.is_shipping,g.is_presell,
          g.promote_goods_number, g.promote_today_number, g.promote_number," ." IFNULL(mp.user_price, g.shop_price * ".$user_rank['discount'].") AS shop_price
           FROM " . C('DB_PREFIX') . "goods_wid_{$wid} AS g " ." LEFT JOIN " . C('DB_PREFIX') . "member_price AS mp " ."ON mp.goods_id = g.goods_id AND mp.user_rank = ".$user_rank['user_rank']." " ." WHERE g.goods_id = '$goods_id'" ." AND g.is_delete = 0 limit 1";
        $goods = $Model->query($sql);
        return $goods[0];
    }

    /**
     * 获取购物车中指定商品信息
     * @param int $uid 用户ID
     * @param int $goods_id 商品ID
     * @param string $spec 商品属性
     */
    public function get_goods_info($uid,$goods_id,$spec,$act_type,$act_id){
        global $is_cashier;
        global $cashier_id;
        if($act_type=='is_exchange'){
            $where=" AND giving in('1','2') ";
        }else if($act_type=='is_quota'){
            $where=" AND giving='3' ";
        }
        //        促销价
        else if ($act_type == 'is_promote') {
            $where = ' AND giving = 4';
        }
        //		秒杀价
        else if ($act_type == 'is_buynow'){
            $where = ' AND giving = 5';
        }
        else{
            $where=" AND giving='0' ";
        }

        if($act_id!=0){
            $where.=" AND act_id=".$act_id;
        }

        $Model=new Model();
        $sql = "SELECT rec_id,goods_number,act_id,giving,is_check FROM " . C('DB_PREFIX') ."cart WHERE user_id = '" . $uid . "' AND goods_id = '$goods_id' " ." $where " ." AND parent_id = 0 AND goods_attr = '" . D('Goods')->get_goods_attr_info($spec) . "' " ." AND extension_code <> 'package_buy' " ." AND rec_type = '" . CART_GENERAL_GOODS . "' and is_cashier='".$is_cashier."' and cashier_id='".$cashier_id."'";

        $row = $Model->query($sql);
        return $row[0];
    }


    /**
     * 获取商品最小购买数量
     * @param int $goods_id 商品ID
     * @return int;
     */
    public function min_buy_num($goods_id){
        global $is_cashier;
        $min_buy_num = 1;
        if($is_cashier!=1) {
            $min_buy_num = D('goods')->where(array('goods_id' => $goods_id))->getField('min_buy_num');
        }
        return $min_buy_num;
    }

    /**
     * 检验数量是否有效
     * @param $goods_id
     * @param $wid
     * @param $num
     * @return array
     */
    public function check_num_valid($goods_id,$wid,$num){

        $min_buy_num = $this->min_buy_num($goods_id);
        $arrGoods = M('goods_wid_'.$wid)->field('is_negative_to_sell,negative_to_sell_start_time,negative_to_sell_end_time,offline_can_buy,goods_name,goods_number,extension_code,is_on_sale,is_presell,goods_sn')->where(array('goods_id'=>$goods_id))->find();
        if(!$arrGoods['is_on_sale'] && $arrGoods['offline_can_buy'] == 0){
                return array('status'=>0,'msg'=>'商品已下架');
        }
        $arrGoods['is_presell']=(int)$arrGoods['is_presell'];

        if($arrGoods['is_presell']!=0 || $arrGoods['is_negative_to_sell']==1){
            //检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
            $is_presell=D('Goodsstorage')->check_whether_presell($goods_id,$wid,1);
        }

        $now=date("Y-m-d H:i:s");
        if($is_presell==1 && $arrGoods['is_negative_to_sell']==1 && $arrGoods['negative_to_sell_start_time']<=$now && $arrGoods['negative_to_sell_end_time']>=$now || empty($wid)){
            //return array('status'=>0,'msg'=>'暂不支持预售');
            //金蝶系统暂不支付预售


            if ($arrGoods ['extensioan_code'] != 'package_buy') {
                if ($arrGoods ['goods_number'] < $num) {
                    if($num == $min_buy_num ){
                        return array('status'=>0,'msg'=>$arrGoods ['goods_name'].'库存仅剩'.$arrGoods ['goods_number'].'份');
                    }else{
                        return array('status'=>0,'msg'=>'已达当前可购买的数量');
                    }

                }
            }
        }elseif($wid){

            if(in_array($wid,C('K3_Wid'))) {
                $kingDee = new KingdeeService();
                $goods_practical_num = $kingDee->getGoodsStockByGoodsSn($wid, $arrGoods['goods_sn']);
                if ($goods_practical_num['code'] != 200) {
                    $goods_practical_num['practical_num'] = 0;
                } else {
                    $goods_practical_num['practical_num'] = $goods_practical_num['data'][$arrGoods['goods_sn']];
                }
            }else{
                $goods_practical_num = D('Goodsstorage')->get_warehous_goods($wid,$goods_id,1);
            }


            if($goods_practical_num['practical_num']<$num){
                if($num == $min_buy_num ){
                    return array('status'=>0,'msg'=>$arrGoods ['goods_name'].'库存仅剩'.$goods_practical_num['practical_num'].'份');
                }else{
                    return array('status'=>0,'msg'=>'已达当前可购买的数量');
                }
            }
        }

        return array('status'=>1);
    }

    /**
     * 删除购物车商品记录
     * @param int $uid 用户ID
     * @param int $rec_id 购物车记录ID
     * @return boolean
     */
    public function remove_shopping_cart_goods($uid,$rec_id){

        $res=$this->flow_drop_cart_goods($rec_id, $is_hd, $uid);
        if($res){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 删除购物车中的商品
     *
     * @access public
     * @param integer $id
     * @param $is_hd 是否为HD请求，0为h5请求；1为HD请求；
     * @param $uid 用户ID；
     * @return void
     */
    function flow_drop_cart_goods( $id, $is_hd=0, $uid = 0 ) {
        global $is_cashier;
        global $cashier_id;
        /* 取得商品id */
        $sql = "SELECT * FROM " . C('DB_PREFIX') . "cart WHERE rec_id = '$id'";
        //        dd($sql);
        $Model=new Model();
        $row = $Model->query($sql);
        $row = $row[0];
        if ($row) {
            // 如果是超值礼包
            if ($row ['extension_code'] == 'package_buy') {
                $sql = "DELETE FROM " . C('DB_PREFIX'). "cart WHERE user_id = '" . $uid . "' " . "AND rec_id = '$id' LIMIT 1";
            }
            // 如果是普通商品，同时删除所有赠品及其配件
            elseif ($row ['parent_id'] == 0) {
                /* 检查购物车中该普通商品的不可单独销售的配件并删除 */
                $sql = "SELECT c.rec_id
				FROM " . C('DB_PREFIX') . "cart AS c, " . C('DB_PREFIX') . "group_goods AS gg, " . C('DB_PREFIX') . "goods AS g
				WHERE gg.parent_id = '" . $row ['goods_id'] . "'
				AND c.goods_id = gg.goods_id
				AND c.parent_id = '" . $row ['goods_id'] . "'
				AND c.extension_code <> 'package_buy'
				AND gg.goods_id = g.goods_id
				AND g.is_alone_sale = 0 
				and c.is_cashier='".$is_cashier."' 
				and c.cashier_id='".$cashier_id."'";
                $res = $Model->query($sql);
                $_del_str = $id . ',';
                foreach ($res as $key=>$id_alone_sale_goods) {
                    $_del_str .= $id_alone_sale_goods ['rec_id'] . ',';
                }
                $_del_str = trim($_del_str, ',');
                $sql = "DELETE FROM " . C('DB_PREFIX') . "cart WHERE rec_id IN ($_del_str) OR parent_id = '$row[goods_id]'";
            }
            // 如果不是普通商品，只删除该商品即可
            else {
                $sql = "DELETE FROM " . C('DB_PREFIX') . "cart WHERE rec_id = '$id' LIMIT 1";
            }
            $Model->execute($sql);
        }else{
            return false;
        }
        //删除购物车中不能单独销售的商品
        $this->flow_clear_cart_alone( $is_hd, $uid );
        return true;
    }

    /**
     * 删除购物车中不能单独销售的商品
     *
     * @access public
     * @param $is_hd hd请求标志，0为H5请求；1为HD请求；
     * @param $uid 用户ID；
     * @return void
     */
    function flow_clear_cart_alone( $is_hd=0, $uid=0 ) {
        global $is_cashier;
        global $cashier_id;
        /* 查询：购物车中所有不可以单独销售的配件 */
        $sql = "SELECT c.rec_id, gg.parent_id
    		FROM " . C('DB_PREFIX') . "cart AS c
    		LEFT JOIN " . C('DB_PREFIX') . "group_goods AS gg ON c.goods_id = gg.goods_id
    		LEFT JOIN " . C('DB_PREFIX') . "goods AS g ON c.goods_id = g.goods_id
    		WHERE c.user_id = '" . $uid . "'
    		AND c.extension_code <> 'package_buy'
    		AND gg.parent_id > 0
    		AND g.is_alone_sale = 0 
    		and c.is_cashier='".$is_cashier."' 
    		and c.cashier_id='".$cashier_id."'";

        $Model=new Model();
        $res = $Model->query($sql);
        $rec_id = array();
        foreach ($res as $key=>$row) {
            $rec_id [$row ['rec_id']] [] = $row ['parent_id'];
        }
        if (empty($rec_id)) {
            return;
        }

        /* 查询：购物车中所有商品 */
        $sql = "SELECT DISTINCT goods_id
    		FROM " . C('DB_PREFIX') .
            "cart WHERE user_id = '" . $uid . "'
    		AND extension_code <> 'package_buy' and is_cashier='".$is_cashier."' and cashier_id='".$cashier_id."'";

        $res = $Model->query($sql);
        $cart_good = array();
        foreach ($res as $key=>$row) {
            $cart_good [] = $row ['goods_id'];
        }
        if (empty($cart_good)) {
            return;
        }

        /* 如果购物车中不可以单独销售配件的基本件不存在则删除该配件 */
        $del_rec_id = '';
        foreach ($rec_id as $key => $value) {
            foreach ($value as $v) {
                if (in_array($v, $cart_good)) {
                    continue 2;
                }
            }

            $del_rec_id = $key . ',';
        }
        $del_rec_id = trim($del_rec_id, ',');

        if ($del_rec_id == '') {
            return;
        }

        /* 删除 */

        /// HD请求处理
        $sql = "DELETE FROM " . C('DB_PREFIX') .
            "cart WHERE user_id = '" . $uid . "'
        AND rec_id IN ($del_rec_id)";

        $Model->execute($sql);
    }

    /**
     * 清空购物车
     * @param   int     $type   类型：默认普通商品
     */
    public function clear_cart($uid,$type = CART_GENERAL_GOODS,$rec_ids='') {
        $map = array('user_id'=>$uid,'rec_type'=>$type);
        if(!empty($rec_ids)){
            $where['rec_id'] = array('in',explode(',', $rec_ids));
            $where['parent_id'] = array('in',explode(',', $rec_ids));
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        }
        $res = $this->where($map)->delete();
    }

    /**
     * 检查商品是否需要传属性
     * @param int $goods_id 商品ID
     * @param string $spec 商品属性
     */
    public function check_spec($goods_id,$spec){


        // 检查：如果商品有规格，而post的数据没有规格，把商品的规格属性通过JSON传到前台
        if (empty($spec)) {
            $Model=new Model();
            $sql = "SELECT a.attr_id, a.attr_name, a.attr_type," . "g.goods_attr_id, g.attr_value, g.attr_price " . 'FROM ' . C('DB_PREFIX') . 'goods_attr AS g ' . 'LEFT JOIN ' . C('DB_PREFIX') . 'attribute AS a ON a.attr_id = g.attr_id ' . "WHERE a.attr_type != 0 AND g.goods_id = '" . $goods_id . "' " . 'ORDER BY a.sort_order, g.attr_price, g.goods_attr_id';
            $res = $Model->query($sql);
            if (!empty($res)) {
                $spe_arr = array();
                foreach ($res as $key=>$row) {
                    $spe_arr [$row ['attr_id']] ['attr_type'] = $row ['attr_type'];
                    $spe_arr [$row ['attr_id']] ['name'] = $row ['attr_name'];
                    $spe_arr [$row ['attr_id']] ['attr_id'] = $row ['attr_id'];
                    $spe_arr [$row ['attr_id']] ['values'] [] = array(
                        'label' => $row ['attr_value'],
                        'price' => $row ['attr_price'],
                        'format_price' => price_format($row ['attr_price'], false),
                        'id' => $row ['goods_attr_id']
                    );
                }
                $i = 0;
                $spe_array = array();
                foreach ($spe_arr as $row) {
                    $spe_array [] = $row;
                }
                return array('status'=>0,'msg'=>$spe_array);
            }
        }
        return array('status'=>1);
    }


    /**
     * 判断 购物车指定记录 是否存在
     * @param number $uid 用户ID；
     * @param number $goods_id 商品ID；
     * @return boolean true存在；false不存在；
     * @author 43
     */
    public function is_exists_record( $uid, $goods_id,&$act_id=0,$act_type="",$goods_attr_id=0) {
        global $is_cashier;
        global $cashier_id;
        $where["goods_id"] = $goods_id;
        $where["user_id"] = $uid;
        $where["can_handsel"] = 0;
        $where["goods_attr_id"] = $goods_attr_id;
        $where['act_id'] = $act_id;
        $where['is_cashier'] = $is_cashier;
        $where['cashier_id'] = $cashier_id;

        if($act_id!=0){
            $where['act_id'] = $act_id;
        }else{
            $cart_act_id = M("Cart")->where(array('user_id'=>$uid,'goods_id'=>$goods_id,'giving'=>array('in','0,4'),'is_cashier'=>$is_cashier,'cashier_id'=>$cashier_id))->getField("act_id");

            if($cart_act_id!=null){
                $where['act_id'] = $cart_act_id;
                $act_id=$cart_act_id;
            }
        }

        if($act_type=='is_exchange'){
            $where["giving"]=array('in','1,2');
        }else if($act_type=='is_quota'){
            $where["giving"]='3';
        }
        else if($act_type == 'is_promote')
        {
            $where['giving'] = '4';
        }
        else if($act_type == 'is_buynow')
        {
            $where['giving'] = '5';
        }
        else
        {
            $where["giving"]='0';
        }


        $info = M("Cart")->where($where)->find();

        if( !empty($info) ) {
            return $info;
        }else {
            return false;
        }
    }

    /**
     * 调用购物车信息
     *
     * @access  public
     * @param $uid 用户ID；
     * @return  string
     */
    public function insert_cart_info($uid = 0 ,$have_gift=true) {
        global $is_cashier;
        global $cashier_id;
        if(!$have_gift){
            $is_gift = " AND is_gift = 0";
        }
        $sql = 'SELECT SUM(goods_number) AS number, SUM(goods_price * goods_number) AS amount' .' FROM ' . C('DB_PREFIX') . 'cart ' ." WHERE user_id = '" . $uid . "' AND rec_type = '" . CART_GENERAL_GOODS . "'".$is_gift." and is_cashier='".$is_cashier."' and cashier_id='".$cashier_id."'";

        $Model=new Model();
        $row = $Model->query($sql);

        $row=$row[0];
        if ($row) {
            $number = intval($row['number']);
            $amount = floatval($row['amount']);
        } else {
            $number = 0;
            $amount = 0;
        }

        return array('number'=>$number,'amount'=>$amount);
        /*$str = sprintf(L('cart_info'), $number, price_format($amount, false));

        return '<a href="flow.php" title="' . L('view_cart') . '">' . $str . '</a>';*/
    }

    /**
     * 调用购物车信息2
     *
     * @access  public
     * @param $uid 用户ID；
     * @return  string
     */
    public function insert_cart_info2($uid,$wid) {
        $favourable_list = $this->favourable_list_flow($uid,$wid);
        $cart_goods = $this->get_cart_goods($uid,$wid,0,$favourable_list);

        return array('number'=>(int)$cart_goods['total']['cart_total_number'],'amount'=>(float)sprintf("%.2f",$cart_goods['total']['cart_total_amount']));
        /*$str = sprintf(L('cart_info'), $number, price_format($amount, false));

        return '<a href="flow.php" title="' . L('view_cart') . '">' . $str . '</a>';*/
    }



    /**
     * 获取当前购物车的商品数
     * @param	int $uid
     */
    public function get_cart_count($uid){
        global $is_cashier;
        global $cashier_id;
        $count = M('Cart')->where(array('user_id'=>$uid,'is_cashier'=>$is_cashier,'cashier_id'=>$cashier_id))->count();
        return $count;
    }




    /*
     * 限购商品购物车增减
     */
    public function change_quota_shopping_cart($act_id,$uid,$goods_id,$current_num,$num=1,$wid=0){
        $activity = D ( 'favourable_activity' );
        $cart = D('cart');
        $favourable = $activity->favourable_info($act_id);

        if (empty($favourable)) {
            returnApiError('优惠活动不存在');
        }
        /* 判断活动类型 */
        if ($favourable ['act_type'] <> 3) {
            returnApiError('活动类型不匹配！');
        }

        /* 判断活动日期是否有效 */
        $time = gmtime();
        if ($time < $favourable['_start_time'] || $time > $favourable['_end_time']) {
            returnApiError('当前活动未开始或已过期');
        }

        /* 判断用户能否享受该优惠 */
        if (! $cart->favourable_available ( $favourable, $uid )) {
            returnApiError ( '您不能享受该优惠' );
        }

        /* 检查是否选择了产品 */
        if (empty ( $goods_id )) {
            returnApiError ( '请选择限购商品' );
        }

        /* 检查产品是否有效 */
        $quota_goods = array ();
        foreach ( $favourable ['quota'] as $item ) {
            if ($item ['id'] == $goods_id) {
                $quota_goods = $item;
                break;
            }
        }

        if (empty ( $quota_goods )) {
            returnApiError ( '没有匹配的商品');
        }
        if($num>0){
            // 查询：系统启用了库存，检查输入的商品数量是否有效
            $goodsnmber=$current_num+$num;
            $arrGoods = D('goods_wid_'.$wid)->field('is_negative_to_sell,negative_to_sell_start_time,negative_to_sell_end_time,offline_can_buy,goods_name,goods_number,extension_code,is_on_sale,is_presell,goods_sn')->where(array('goods_id'=>$goods_id))->find();
            if(!$arrGoods['is_on_sale']&& $arrGoods['offline_can_buy'] == 0){
                returnApiError('商品已下架');
            }
            $arrGoods['is_presell']=(int)$arrGoods['is_presell'];
            if($arrGoods['is_presell']!=0 || $arrGoods['is_negative_to_sell']==1){
                //检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
                $is_presell=D('Goodsstorage')->check_whether_presell($goods_id,$wid,1);
            }
            $now=date("Y-m-d H:i:s");
            if($is_presell && $arrGoods['is_negative_to_sell']==1 && $arrGoods['negative_to_sell_start_time']<=$now && $arrGoods['negative_to_sell_end_time']>=$now){
                //returnApiError('暂不支持预售');
                //金蝶系统暂不支付预售
                if (intval(C('use_storage')) > 0 && $arrGoods ['extension_code'] != 'package_buy') {
                    if ($arrGoods ['goods_number'] < $goodsnmber) {
                        returnApiError($arrGoods ['goods_name'].'库存仅剩'.$arrGoods ['goods_number'].'份');
                    }
                }
            }elseif($wid){

                if(in_array($wid,C('K3_Wid'))) {
                    $kingDee = new KingdeeService();
                    $goods_practical_num = $kingDee->getGoodsStockByGoodsSn($wid, $arrGoods['goods_sn']);
                    if ($goods_practical_num['code'] != 200) {
                        $goods_practical_num['practical_num'] = 0;
                    } else {
                        $goods_practical_num['practical_num'] = $goods_practical_num['data'][$arrGoods['goods_sn']];
                    }
                }else{
                    $goods_practical_num = D('Goodsstorage')->get_warehous_goods($wid,$goods_id,1);
                }
                if($goods_practical_num['practical_num']<$goodsnmber){
                    returnApiError($arrGoods ['goods_name'].'库存仅剩'.$goods_practical_num['practical_num'].'份');
                }
            }
            /* 限购类型(全局或者指定产品) */
            $count = round($favourable['act_type_ext']);
            if ($count > 0) {
                /* 检查购物车中是否已有该优惠 */
                $cart_favourable = $cart->cart_favourable_quota($act_id,'',$uid);
                if ($cart_favourable && $cart_favourable['num'] >= $count) {
                    returnApiError("此活动限购" . $count . "份，您已加入购物车" . $cart_favourable['num'] . "份");
                }
                /* 检查是否已参与过该活动 */
                $quota_favourable = $cart->activity_favourable_quota($act_id,'',$uid);
                if ($quota_favourable && $quota_favourable['num'] >= $count) {
                    returnApiError("此活动您已参与过");
                }
            } else {
                /* 检查购物车中是否已有该优惠 */
                $cart_favourable = $cart->cart_favourable_quota($act_id, $goods_id,$uid);
                if ($cart_favourable && $cart_favourable['num'] >= $quota_goods['count']) {
                    returnApiError("此产品限购'$quota_goods[count]'份，您已加入购物车" . $cart_favourable['num'] . "份");
                }
                /* 检查是否已参与过该活动 */
                $quota_favourable = $cart->activity_favourable_quota($act_id, $goods_id,$uid);
                if ($quota_favourable && $quota_favourable['num'] >= $quota_goods['count']) {
                    returnApiError("此活动您已参与过");
                }
            }
        }

        /* 修改到购物车 */
        $res = $cart->change_quota_to_cart($act_id, $quota_goods ['id'], $quota_goods ['price']*$num,$uid,$num);
    }


    /**
     * 获取分类ID/名称
     * @param string $act_range_ext 分类ID串
     */
    public function get_act_cate_info($act_range_ext){
        $Model=new Model();
        $sql = 'SELECT cat_id,cat_name FROM ' . C('DB_PREFIX') . 'category ' ." WHERE cat_id in(".$act_range_ext.") order by sort_order asc";
        $row = $Model->query($sql);
        if($row[0]){
            return $row;
        }else{
            return '';
        }
    }

    /**
     * 获取品牌ID\名称
     * @param string $act_range_ext 品牌ID串
     */
    public function get_act_brand_info($act_range_ext){
        $Model=new Model();
        $sql = 'SELECT brand_id,brand_name FROM ' . C('DB_PREFIX') . 'brand ' ." WHERE brand_id in(".$act_range_ext.") order by sort_order asc";
        $row = $Model->query($sql);
        if($row[0]){
            return $row;
        }else{
            return '';
        }
    }

    /**
     * 返回最新商品价格并修改
     * Created by Jerry
     * @param $goods_id
     * @param $cart_id
     * @return mixed
     */
    protected function update_cart_goods_price($goods_id, $cart_id){
        //        查询商品价格
        $goodsModel = D('Goods');
        $goods_price = $goodsModel->get_final_price($goods_id);

        $where = array(
            'rec_id'    =>  $cart_id,
        );
        $updateData = array(
            'goods_price'   =>  $goods_price,
        );
        $rs = M("cart")->where($where)->save($updateData);

        return $goods_price;
    }


    /**
     * 取得红包信息
     * @param $bonus_id 红包id
     * @param string $bonus_sn  红包序列号
     * @param int $bonus_type
     * @return bool 红包信息
     */
    public function bonus_info($bonus_id, $bonus_sn = '',$bonus_type = 0) {
        $sql = "SELECT t.*, b.* " .
            "FROM " . C('DB_PREFIX') . "bonus_type AS t," .
            C('DB_PREFIX') . "user_bonus AS b " .
            "WHERE t.type_id = b.bonus_type_id AND t.bonus_type = ".$bonus_type;
        if ($bonus_id > 0) {
            $sql .= " AND b.bonus_id = '$bonus_id'";
        } else {
            $sql .= " AND b.bonus_sn = '$bonus_sn'";
        }
        $sql .=' limit 1';
        $Model=new Model();
        $row=$Model->query($sql);
        $bouns = $row[0];
        $now = gmtime();
        if(($bouns['deadline']>0 && $bouns['deadline']<$now) || ($bouns['deadline']==0 && $bouns['use_end_date']<$now)){
            $bouns = false;
        }

        return $bouns;
    }


    /**
     * 检查购物车商品是否有价格变动
     * @param $cart_goods
     * @param $uid
     * @param $show_return
     */
    public function check_goods_price($cart_goods,$uid,$show_return=true){
        //    	dd($cart_goods);
        if(count($cart_goods)>0){
            $cart_goods_list = array();
            $have_change = false;
            $msg = '购物车中商品价格有变动';
            $user_rank = M('users')->where(array("user_id"=>$uid))->getField('user_rank');
            foreach($cart_goods as $goods){

                if($goods['is_quota']>0){
                    $res = $this->check_quota_price($goods,$uid,$goods['is_quota']);
                }
            elseif($goods['is_gift']>0)
                {
                    $res = $this->check_gift_price($goods,$uid,$goods['is_gift']);
                }
                //    			else if ($goods['giving'] == 4)
                //    			{
                //					$res = $this->check_promote_price($goods);
                //				}
                else
                {
                    $res = $this->check_normal_goods_price($goods,$uid,$user_rank);
                }
                if($res['have_change']==1){
                    $cart_goods_list[] = $res['cart_goods'];
                    $have_change = true;
                }
            }

            if($have_change && $show_return){
                returnApiError($msg,$cart_goods_list);
            }
        }
    }

    /**
     * 抢购商品购物车价格变动检查
     * @param $goods
     * @param $uid
     * @param $act_id
     * @return array
     */
    private function check_quota_price($goods,$uid,$act_id){
        $result = array('have_change'=>0);
        $activity = D ( 'favourable_activity' );
        $favourable = $activity->favourable_info($goods['is_quota']);

        if(!empty($favourable['quota'])){
            $favourable_goods_list = $favourable['quota'];
            foreach ($favourable_goods_list as $favourable_goods){
                if($favourable_goods['id']==$goods['goods_id'] && ($favourable_goods['price']-$goods['goods_price']!=0)){
                    $goods_price = $favourable_goods['price'];
                    D('cart')->where(array('rec_id'=>$goods['rec_id']))->setField('goods_price',$goods_price);
                    $goods['new_goods_price'] = $goods_price;
                    $result['have_change'] = 1;
                    $result['cart_goods'] = $goods;
                }
            }
        }

        return $result;
    }

    /**
     * 赠送或优惠商品购物车价格变动检查
     * @param $goods
     * @param $uid
     * @param $act_id
     * @return array
     */
    private function check_gift_price($goods,$uid,$act_id){
        $result = array('have_change'=>0);
        $activity = D ( 'favourable_activity' );
        $favourable = $activity->favourable_info($goods['is_gift']);

        if(!empty($favourable['gift'])){
            $favourable_goods_list = $favourable['gift'];
            foreach ($favourable_goods_list as $favourable_goods){
                if($favourable_goods['id']==$goods['goods_id'] && ($favourable_goods['price']-$goods['goods_price']!=0)){
                    if($goods['goods_price']==0){
                        M('cart')->where(array('rec_id'=>$goods['rec_id']))->delete();
                    }elseif($favourable_goods['price']==0){
                        M('cart')->where(array('rec_id'=>$goods['rec_id']))->delete();
                    }else{
                        $goods_price = $favourable_goods['price'];
                        M('cart')->where(array('rec_id'=>$goods['rec_id']))->setField('goods_price',$goods_price);
                    }
                    $goods['new_goods_price'] = $goods_price;
                    $result['have_change'] = 1;
                    $result['cart_goods'] = $goods;
                }
            }
        }

        return $result;
    }

    /**
     * 普通商品购物车价格变动检查
     * @param $goods
     * @param $uid
     * @param $user_rank
     * @return array
     */
    private function check_normal_goods_price($goods,$uid,$user_rank){
        $result = array('have_change'=>0);
        $map = array();
        $spec = "";

        if($goods['goods_attr_id']){
            $spec = explode(',', $goods['goods_attr_id']);
        }
        if($goods['giving'] !=6) {
            $goods_price = D('Goods')->get_final_price($goods['goods_id'], $goods['goods_number'], true, $spec, $uid);
        }
        ////		促销价
        //		$promote_price = bargain_price($goods['promote_price'], $goods['promote_start_date'], $goods['promote_end_date']);
        //		if ($promote_price > 0 && ($goods_price - $goods['promote_price'] != 0)) {
        //			returnApiError('促销商品价格和数量有所变动');
        //		}


        if ($goods['giving'] > 0 && $goods['giving'] !=6) {

            if ($goods['is_buynow'] == 0) {
                $promoteService = new PromoteService();
                $status = $promoteService->getPromotePriceStatus($goods);

                if ($status) {
                    $this->isPriceChange($goods, $goods_price, $uid);
                }
                else{
                    D('cart')->where(array('rec_id'=>$goods['rec_id']))->setField('giving', 0);
                }
            }
            else if($goods['is_buynow'] == 1){
                $buyNowGoodsService = new BuyNowGoodsRepository($uid);
                $status = $buyNowGoodsService->getBuyNowGoodsData($goods);
                if ($status['buy_now_status'] == 3) {
                    $this->isPriceChange($goods, $goods_price, $uid);
                }
            }
        }
        if(($goods_price - $goods['goods_price']) != 0){
            D('cart')->where(array('rec_id'=>$goods['rec_id']))->setField('goods_price',$goods_price);
            $goods['new_goods_price'] = $goods_price;
            $result['have_change'] = 1;
            $result['cart_goods'] = $goods;
        }
        return $result;
    }

    /**
     * 检测价格变动
     * Created by Jerry
     * @param $goods
     * @param $goods_price
     * @param int $uid
     * @return bool
     */
    protected function isPriceChange($goods, $goods_price, $uid = 0)
    {
        $promoteService = new PromoteService();
        $promote_price = $promoteService->checkPromotePriceRank($goods['goods_id'], $uid);

        if ($promote_price > 0 && ($goods_price - $goods['promote_price'] != 0)) {
            //            returnApiError('商品价格和数量有所变动');
            return false;
        }

        return true;
    }

    /**检测活动赠品
     * @param cart_info
     * @param num
     * @param goods_id
     * @param act_info
     */
    public function check_act_giving_goods($uid,$wid,$cart_info,$act_info)
    {
        $num=$cart_info['goods_number'];
        $goods_id=$cart_info['goods_id'];
        $is_check=$cart_info['is_check'];
        $act_id=$cart_info['act_id'];
        $gift=unserialize($act_info['gift']);
        foreach($gift as $item){
            $goods_id_list[]=$item['id'];
            $goods_price_list[]=$item['price'];
            $goods_list[$item['id']]=$item['price'];
        }


        if($act_info['act_range']==3 && is_numeric($act_info['act_range_ext']) && count($gift)==1 && $act_info['act_type']==0 && floatval($act_info['min_amount'])==0 && $goods_list[$gift[0]['id']]==0 && $is_check=='1'){

            //买一赠一
            if($num>$act_info['act_type_ext'] && floatval($act_info['act_type_ext'])!=0){
                $change_num=$act_info['act_type_ext'];
            }else{
                $change_num=$num;
            }
            $change_num1=$change_num;
            if($gift[0]['id']==$goods_id){
                $change_num1=$change_num*2;
            }

            $is_valid_true=$this->check_num_valid($gift[0]['id'],$wid,$change_num1);
            if($is_valid_true['status']){

                $re_msg=$this->change_cart($uid,$gift[0]['id'],$change_num,array(),$wid,$act_id,'is_exchange',0);
                if(!$re_msg['status']){
                    return $re_msg;
                }
            }
        }else if(count($gift)==1 && $act_info['act_type']==0 && $goods_list[$gift[0]['id']]==0 && $is_check=='1'){
            $change_num1=1;
            if($gift[0]['id']==$goods_id){
                $change_num1=$num+1;
            }

            $is_valid_true=$this->check_num_valid($gift[0]['id'],$wid,$change_num1);
            if($is_valid_true['status']){
                $re_msg=$this->change_cart($uid,$gift[0]['id'],1,array(),$wid,$act_id,'is_exchange',0);
                if(!$re_msg['status']){
                    return $re_msg;
                }
            }
        }
    }

    /**
     * @param $cart_goods
     * @param $flag
     * @param $bonus_id
     * @param $cart_goods_info_temp
     * @param $bonus
     * @return array
     */
    public function get_bonus_proportion(&$cart_goods, $bonus_id)
    {

        $bonus_info = M("user_bonus")->alias("b")->join("left join sdx_bonus_type as t on t.type_id = b.bonus_type_id")->where(array('bonus_id' => $bonus_id))->Field("t.type_id,t.type_money,t.is_limit_buy,t.include_promotion,bonus_discount_type")->find();

        $config = M('bonus_config')->where(array("bonus_type_id" => $bonus_info["type_id"], "status" => 1))->select();

        $goods_total = 0;
        $bonus_goods_proportion=1;
        $bonus_goods_num=0;


        if(empty($config)){
            $bonus_info['is_limit_buy']=0;
        }


        foreach ($cart_goods as $key => $row) {

            $flag = false;

            if($row['giving']==1){
                continue;
            }

            if(isset($row['use_bonus']) && $row['use_bonus']==0){
                continue;
            }

            if($bonus_info['is_limit_buy']==0){
                $flag = true;

            }

            if($row['giving']==4 && $bonus_info['include_promotion']==0){
                continue;
            }

            if (!empty($config)) {

                foreach ($config as $cfg_key => $val_cfig) {


                    switch ($val_cfig['act_rang']) {
                        case 1:
                            $cate_id_arr=array($val_cfig['cate_id']);
                            $cate_id_list = M('category')->where(array("parent_id" => $val_cfig['cate_id']))->select();
                            foreach($cate_id_list as $itemcid){
                                $cate_id_arr[]=$itemcid['cat_id'];
                                $cate_id_list2 = M('category')->where(array("parent_id" => $itemcid['cat_id']))->select();
                                foreach($cate_id_list2 as $itemcid2) {
                                    $cate_id_arr[] = $itemcid2['cat_id'];
                                }
                            }

                            if (in_array($row['cat_id'],$cate_id_arr)) {
                                $flag = true;
                            }
                            break;
                        case 2:
                            if ($val_cfig['brand_id'] == $row['brand_id']) {
                                $flag = true;
                            }
                            break;
                        case 3:
                            if ($val_cfig['goods_id'] == $row['goods_id']) {
                                $flag = true;
                            }
                            break;
                    }
                }
            }
            $cart_goods[$key]['use_bonus'] = 0;
            if ($flag) {
                $goods_total += $row['goods_price'] * $row['goods_number'];
                $cart_goods[$key]['use_bonus'] = 1;
                $bonus_goods_num++;
            }


        }

        if($bonus_info['bonus_discount_type']==2){
            $bonus_goods_proportion = $bonus_info['type_money']/10;
            $bonus_money=$goods_total*((10-$bonus_info['type_money'])/10);
        }else if($bonus_info['bonus_discount_type']==1){
            $bonus_goods_total = $goods_total - $bonus_info['type_money'];
            $bonus_goods_proportion = $bonus_goods_total / $goods_total;
            $bonus_money=$bonus_info["type_money"];
        }



        return array('bonus_goods_proportion'=>$bonus_goods_proportion,'bonus_goods_num'=>$bonus_goods_num,'bonus_money'=>$bonus_money,'bonus_info'=>$bonus_info);
    }

    /**添加充值赠品到购物车
     * @int $user_id
     * @array $goods_info[goods_id,goods_sn,goods_name,market_price,goods_number,expiration_date]
     * @return bool
     */
    public function add_recharge_giving_to_cart($user_id,$goods_info){
        if($goods_info['expiration_date']>gmtime()){
            $cartdata=array();
            $cartdata['user_id']=$user_id;
            $cartdata['goods_id']=$goods_info['goods_id'];
            $cartdata['goods_sn']=$goods_info['goods_sn'];
            $cartdata['goods_name']=$goods_info['goods_name'];
            $cartdata['market_price']=$goods_info['market_price'];
            $cartdata['goods_price']=0;
            $cartdata['goods_number']=$goods_info['goods_number'];
            $cartdata['expiration_date']=$goods_info['expiration_date'];
            $cartdata['is_real']=1;
            $cartdata['giving']=6;
            $cartdata['is_check']=1;
            $cartdata['act_id']=0;
            M("cart")->add($cartdata);
            return true;
        }
        return false;
    }

    /**
     * @param $goods_ids array 商品ids
     * @param $wid  int 仓库id
     * @return mixed 购物车商品的促销价
     */
    public function getPromotePrice($goods_ids,$wid){
        $promote = D('goods')->alias('g')
            ->field("w.promote_price,w.promote_start_date,w.promote_end_date,g.goods_id,IFNULL(mp.user_price,format(g.shop_price*(88/100),2)) as vip_price")
            ->join("left join ".C('DB_PREFIX')."goods_wid_".$wid." w on g.goods_id = w.goods_id")
            ->join("left join ".C('DB_PREFIX')."member_price mp on g.goods_id = mp.goods_id")
            ->where(array('g.goods_id'=>array('in',$goods_ids),'mp.user_rank'=>array('EQ',2)))
            ->select();
        return $promote;
    }

    /**
     * @role 线下活动
     * @param $uid
     * @param $wid
     * @return array
     */
    public function favourable_list_store_flow($uid,$wid){
        if(empty($wid)){
            $wid = C('DEFAULT_WID');
        }
        //获取当前用户等级
        $user_rank = D('users')->where(array('user_id'=>$uid))->getField('user_rank');
        if(empty($user_rank)){
            $user_rank = 1;
        }
        $now = gmtime();

        $map = array();

        $map["start_time"] = array('elt',$now);
        $map["end_time"] = array('egt',$now);
        $map["range_of_activity"]=array('neq',1);
        $map['act_type'] = array('in',array(FAT_GOODS, FAT_PRICE, FAT_DISCOUNT, FAT_DISCOUNT_LIMIT));
        $map['_string'] = "FIND_IN_SET(".$user_rank.", user_rank)";

        //获取当前用户可参与的活动（除抢购外）
        $favourable_activity_list = M('favourable_activity')->where($map)->order('sort_order desc,act_id desc')->select();

        $goods_sn_arr=array();

        foreach ($favourable_activity_list as $key=>$favourable) {

            $favourable ['start_time'] = local_date(C('time_format'), $favourable ['start_time']);
            $favourable ['end_time'] = local_date(C('time_format'), $favourable ['end_time']);
            $favourable ['formated_min_amount'] = price_format($favourable ['min_amount'], false);
            $favourable ['formated_max_amount'] = price_format($favourable ['max_amount'], false);
            $favourable_gift = unserialize($favourable ['gift']);

            $gift_list = array();
            //获取赠品或换购商品图


            foreach($favourable_gift as $key_gift=>$gift){
                $goods = M('goods_wid_'.$wid)->field('goods_sn,goods_img,practical_num as goods_stock,is_on_sale,is_delete,spec_value,spec_unit')->where(array('goods_id'=>$gift['id']))->find();
                if($goods['is_delete']==0){
                    $goods_sn_arr[]=$goods['goods_sn'];
                    $favourable_gift[$key_gift]['goods_sn'] = $goods['goods_sn'];
                    $favourable_gift[$key_gift]['goods_img'] = img_init($goods['goods_img']);
                    $favourable_gift[$key_gift]['goods_stock'] = $goods['goods_stock'];
                    //                    $goods_detail_info = D('goods')->get_goods_detail_info($gift['id'],$user_rank);
                    $favourable_gift[$key_gift]['goods_price'] = D('goods')->get_vip_price_for_all($gift['id'],$user_rank);
                    $favourable_gift[$key_gift]['spec_value'] = $goods['spec_value'];
                    $favourable_gift[$key_gift]['spec_unit'] = $goods['spec_unit'];
                    $gift_list[] = $favourable_gift[$key_gift];
                }
            }





            $favourable ['gift'] = $gift_list;
            $favourable ['quota'] = unserialize($favourable ['quota']);
            $favourable ['act_tag'] = $this->check_activity_tag($favourable ['act_type'],$favourable ['gift'],$favourable ['act_range'],$favourable ['act_range_ext'],$favourable ['min_amount']);
            $favourable['discount'] = json_decode($favourable['discount'], true);
            $favourable_list [] = $favourable;
        }


        if(in_array($wid,C('K3_Wid'))){
            $kingDee=new KingdeeService();
            $goods_practical_num=$kingDee->getGoodsStockByGoodsSn($wid,$goods_sn_arr);
            $goodsstorage_list_k3=$goods_practical_num['data'];

            foreach($favourable_list as $key=>$favourable){
                foreach($favourable['gift'] as $key_gift=>$gift){
                    isset($goodsstorage_list_k3[$gift["goods_sn"]]) ? $favourable_list[$key]['gift'][$key_gift]['goods_stock'] = $goodsstorage_list_k3[$gift["goods_sn"]] : $favourable_list[$key]['gift'][$key_gift]['goods_stock'] = 0;
                }
            }
        }

        return $favourable_list;

    }

    /**
     * @param $goods_ids array 商品ids
     * @param $wid  int 仓库id
     * @return mixed 购物车商品的促销价
     */
    public function getStock($goods_ids,$wid){
        $practical_num = D('goodsstorage')
            ->where(array('goods_id'=>array('EQ',$goods_ids),'wid'=>array('EQ',$wid)))
            ->find();
        return $practical_num;
    }

    /**
     * @description 从redis读取购物车信息
     * @param $uid
     * @param $wid
     * @param int $rec_ids
     * @param int $flow_type
     * @param int $flow_type
     * @return array
     */
//    public function get_redis_goods_by_uid($uid,$wid,$flow_type = CART_GENERAL_GOODS)
//    {
//        //是否收银员
//        global $is_cashier;
//        //收银员id
//        global $cashier_id;
//
//        //获取哈希表名
//        $cart_user_id = 'cart:'.$uid.':store';
//
//        $redis = cRedis();
////        $currentTime = gmtime();
//        //取用户的购物车商品
//        $res = $redis->hGetAll($cart_user_id);
//
//        $keys = array_keys($res);
//        $goods_nums = array_values($res);
//        $goods_desc_stock = $redis->hMGet('cart:goods',$keys);
////        $promote = $this->getPromotePrice($keys,$wid);
//
//        if (empty($keys)) {
//            return array();
//        }
//        //        $cart_list = array();
//        $goods_sns = array();
//        $key_length = count($keys);
//        $error_messsage1 = '';
//        if(in_array($wid,C('K3_Wid'))){
//            //拿到goods_sn
//            foreach ($goods_desc_stock as $key=>$value){
//                $value = json_decode($value,true);
//                $goods_sns[$key] = $value['goods_sn'];
//            }
//            //用金蝶系统判断是否缺货
//            $kingdee = new KingdeeService();
//            $goods_stock = $kingdee->checkStockSingle($wid,$goods_sns);
//            //判断是否缺货
//            foreach ($goods_desc_stock as $goods_key=>$goods_dc){
//                $goods_dc = json_decode($goods_desc_stock[$goods_key],true);
//                $array_sub = array_search($goods_dc['goods_id'],$keys);
//                if($goods_nums[$array_sub] > (int)$goods_stock[$goods_dc['goods_sn']] && $goods_stock[$goods_dc['goods_sn']] != 0){
//                    $redis->hset($cart_user_id,$goods_dc['goods_id'],(int)$goods_stock[$goods_dc['goods_sn']]);
//                    $error_messsage1 = $goods_dc['goods_id'].'购买数量已达到最大库存数，请重新确认购买的数量;';
//                }
//                if($goods_nums[$array_sub] > (int)$goods_stock[$goods_dc['goods_sn']] || $goods_stock[$goods_dc['goods_sn']] <= 0){
//                    if($goods_dc['stock_out'] !=1){
//                        $goods_dc['stock_out'] = 1;
//                        $redis->hset('cart:goods',$goods_dc['goods_id'],json_encode($goods_dc));
//                        $error_messsage1 = $goods_dc['goods_name'].'商品库存已发生变化;';
//                    }
////                    $redis->hset($cart_user_id,$goods_dc['goods_id'],(int)$goods_stock[$goods_dc['goods_sn']]);
////                    $error_messsage1 = $goods_dc['goods_name'].'购买数量已达到最大库存数，请重新确认购买的数量;';
//                }else{
//                    if($goods_dc['stock_out'] != 0){
//                        $goods_dc['stock_out'] = 0;
//                        $redis->hset('cart:goods',$goods_dc['goods_id'],json_encode($goods_dc));
//                        $error_messsage1 = $goods_dc['goods_name'].'商品库存已发生变化;';
//                    }
//                }
//            }
//            if(!empty($error_messsage1)){
//                returnApiError($error_messsage1);
//            }
//        }else{
//            foreach ($goods_desc_stock as $key=>$value){
//                $value = json_decode($value,true);
//                $stock_res = $this->getStock($value['goods_id'],$wid);
//                $practical_num = $stock_res['practical_num'];
//                if($res[$value['goods_id']] > $practical_num && $practical_num != 0){
//                    $redis->hset($cart_user_id,$value['goods_id'],$practical_num);
//                    $error_messsage1 = $value['goods_name'].'购买数量已达到最大库存数，请重新确认购买的数量;';
//                }
//                if($res[$value['goods_id']] > $practical_num || $practical_num <= 0){
//                    if($value['stock_out'] !=1){
//                        $value['stock_out'] = 1;
//                        $redis->hset('cart:goods',$value['goods_id'],json_encode($value));
//                        $error_messsage1 = $value['goods_name'].'商品库存已发生变化;';
//                    }
////                    $redis->hset($cart_user_id,$value['goods_id'],$practical_num);
////                    $error_messsage1 = $value['goods_name'].'购买数量已达到最大库存数，请重新确认购买的数量;';
//                }else{
//                    if($value['stock_out'] != 0){
//                        $value['stock_out'] = 0;
//                        $redis->hset('cart:goods',$value['goods_id'],json_encode($value));
//                        $error_messsage1 = $value['goods_name'].'商品库存已发生变化;';
//                    }
//                }
//            }
//            if(!empty($error_messsage1)){
//                returnApiError($error_messsage1);
//            }
//        }
//        //拼接上商品数量
//        $favourable_list = $this->favourable_list_store_flow($uid,$wid);
//        for($i=0;$i<$key_length;$i++){
//            $goods_desc = json_decode($redis->hget('cart:goods',$keys[$i]),true);
//            try{
//                if($goods_desc['stock_out'] != 1){
//                    foreach ($favourable_list as $fav_value){
//                        $is_many = strpos($fav_value['act_range_ext'],',');
//                        $stock_res = $this->getStock($fav_value['gift'][0]['id'],$wid);
//                        $practical_num = $stock_res['practical_num'];
//                        if(empty($is_many)){
//                            if($fav_value['act_range_ext'] == $goods_desc['goods_id']){
//                                $goods_gift = json_decode($redis->hGet('cart:goods',$fav_value['gift'][0]['id']),true);
//                                $goods_gift['goods_price'] = 0;
//                                $goods_gift['act_id'] = $fav_value['act_id'];
//                                $goods_gift['is_gift'] = $fav_value['act_id'];
//                                $goods_gift['gift'] = 1;
//                                $goods_gift['product_id']=0;
//                                $goods_gift['goods_attr_id']='';
//                                $goods_gift['goods_attr']='';
//                                $goods_gift['is_real']=0;
//                                $goods_gift['parent_id']=0;
//                                $goods_gift['is_quota']=0;
//                                $goods_gift['expiration_date']=0;
//                                $redis_gift_state = $redis->get('cart:gift:state:'.$uid);
//                                if($practical_num <= 0){
//                                    $gift_state = 2;
//                                    if($redis_gift_state != $gift_state){
//                                        $redis->set('cart:gift:state:'.$uid,$gift_state);
//                                        returnApiError('赠品库存已售罄');
//                                    }
//                                }elseif(($fav_value['gift'][0]['num'] * $goods_nums[$i]) > $practical_num){
//                                    $gift_state = 1;
//                                    if($redis_gift_state != $gift_state){
//                                        $redis->set('cart:gift:state:'.$uid,$gift_state);
//                                        returnApiError('赠品库存仅剩'.$practical_num.'件');
//                                    }
//                                    $gift_cache_num = get_queue_goods_stock($fav_value['gift'][0]['id'],$wid);
//                                    if($gift_cache_num != $practical_num){
//                                        set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
//                                        returnApiError('赠品库存仅剩'.$practical_num.'件');
//                                    }
//                                    $goods_gift['goods_number'] = $practical_num;
//                                    $goods_gift['practical_num'] = $practical_num;
//                                    $goods_gift['stock_out'] = 0;
//                                    set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
//                                    $cart_list[] = $goods_gift;
//                                }else{
//                                    $gift_state = 0;
//                                    if($redis_gift_state != $gift_state){
//                                        $redis->set('cart:gift:state:'.$uid,$gift_state);
//                                        returnApiError('大圣把赠品给补齐了，请重新提交订单');
//                                    }
//                                    $goods_gift['goods_number'] = $fav_value['gift'][0]['num'] * $goods_nums[$i];
//                                    $goods_gift['practical_num'] = $practical_num;
//                                    $goods_gift['stock_out'] = 0;
//                                    set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
//                                    $cart_list[] = $goods_gift;
//                                }
//                                $goods_desc['act_id']=$fav_value['act_id'];
//                            }else{
//                                $goods_desc['act_id']=0;
//                            }
//                        }else{
//                            $act_range_ext = explode(',',$fav_value['act_range_ext']);
//                            if(in_array($goods_desc['goods_id'],$act_range_ext)){
//                                $goods_gift = json_decode($redis->hGet('cart:goods',$fav_value['gift'][0]['id']),true);
//                                $goods_gift['goods_price'] = 0;
//                                $goods_gift['act_id'] = $fav_value['act_id'];
//                                $goods_gift['is_gift'] = $fav_value['act_id'];
//                                $goods_gift['gift'] = 1;
//                                $goods_gift['product_id']=0;
//                                $goods_gift['goods_attr_id']='';
//                                $goods_gift['goods_attr']='';
//                                $goods_gift['is_real']=0;
//                                $goods_gift['parent_id']=0;
//                                $goods_gift['is_quota']=0;
//                                $goods_gift['expiration_date']=0;
//                                $redis_gift_state = $redis->get('cart:gift:state:'.$uid);
//                                if($practical_num <= 0){
//                                    $gift_state = 2;
//                                    if($redis_gift_state != $gift_state){
//                                        $redis->set('cart:gift:state:'.$uid,$gift_state);
//                                        returnApiError('赠品库存已售罄');
//                                    }
//                                }elseif(($fav_value['gift'][0]['num'] * $goods_nums[$i]) > $practical_num){
//                                    $gift_state = 1;
//                                    if($redis_gift_state != $gift_state){
//                                        $redis->set('cart:gift:state:'.$uid,$gift_state);
//                                        returnApiError('赠品库存仅剩'.$practical_num.'件');
//                                    }
//                                    $gift_cache_num = get_queue_goods_stock($fav_value['gift'][0]['id'],$wid);
//                                    if($gift_cache_num != $practical_num){
//                                        set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
//                                        returnApiError('赠品库存仅剩'.$practical_num.'件');
//                                    }
//                                    $goods_gift['goods_number'] = $practical_num;
//                                    $goods_gift['practical_num'] = $practical_num;
//                                    $goods_gift['stock_out'] = 0;
//                                    set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
//                                    $cart_list[] = $goods_gift;
//                                }else{
//                                    $gift_state = 0;
//                                    if($redis_gift_state != $gift_state){
//                                        $redis->set('cart:gift:state:'.$uid,$gift_state);
//                                        returnApiError('大圣把赠品给补齐了，请重新提交订单');
//                                    }
//                                    $goods_gift['goods_number'] = $fav_value['gift'][0]['num'] * $goods_nums[$i];
//                                    $goods_gift['practical_num'] = $practical_num;
//                                    $goods_gift['stock_out'] = 0;
//                                    set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
//                                    $cart_list[] = $goods_gift;
//                                };
//                                $cart_list[] = $goods_gift;
//                                $goods_desc['act_id']=$fav_value['act_id'];
//                            }else{
//                                $goods_desc['act_id']=0;
//                            }
//                        }
//                    }
//                }
//            }catch(\Exception $e){
//                returnApiError('服务器繁忙，请稍后再试');
//            }
//            $goods_desc['goods_number'] = $goods_nums[$i];
//            $goods_desc['user_id'] = $uid;
//            $goods_desc['is_check'] = 1;
//            $goods_desc['wid'] = $wid;
//            $goods_desc['expiration_date']=0;
//            $goods_desc['normal_price']=$goods_desc['goods_price'];
//            $goods_desc['product_id']=0;
//            $goods_desc['goods_attr_id']='';
//            $goods_desc['goods_attr']='';
//            $goods_desc['is_real']=1;
//            $goods_desc['is_gift']=0;
//            $goods_desc['is_quota']=0;
//            $goods_desc['extension_code']=0;
//            $goods_desc['parent_id']=0;
//            $goods_desc['giving']="0";
////            $k = array_search($goods_desc['goods_id'],array_column($promote,'goods_id'));
////            if($promote[$k]['promote_start_date'] < $currentTime && $promote[$k]['promote_end_date'] > $currentTime){
////                $goods_desc['promote_price'] = $promote[$k]['promote_price'];
////                $goods_desc['goods_price'] = $promote[$k]['promote_price'];
////                $goods_desc['normal_price'] = $promote[$k]['promote_price'];
////                $goods_desc['giving'] = 4;
////            }else{
////                $goods_desc['goods_price'] = $promote[$k]['vip_price'];
////                $goods_desc['normal_price'] = $promote[$k]['vip_price'];
////                $goods_desc['promote_price'] = 0;
////                $goods_desc['promote_start_date'] = 0;
////                $goods_desc['promote_end_date'] = 0;
////                $goods_desc['giving'] = 0;
////            }
////            array_push($cart_list,$goods_desc);
//            $cart_list[] = $goods_desc;
//
//        }
//        //去除缺货的商品
//        foreach ($cart_list as $key=>$value){
//            if($value['stock_out'] == 1){
//                unset($cart_list[$key]);
//            }
//        }
//        array_values($cart_list);
//        return $cart_list;
//    }
    public function get_redis_goods_by_uid($uid,$wid,$flow_type = CART_GENERAL_GOODS)
    {
        //是否收银员
        global $is_cashier;
        //收银员id
        global $cashier_id;

        //获取哈希表名
        $cart_user_id = 'cart:'.$uid.':store';

        $redis = cRedis();
//        $currentTime = gmtime();
        //取用户的购物车商品
        $res = $redis->hGetAll($cart_user_id);

        $keys = array_keys($res);
        $goods_nums = array_values($res);
        $goods_desc_stock = $redis->hMGet('cart:goods',$keys);
//        $promote = $this->getPromotePrice($keys,$wid);

        if (empty($keys)) {
            return array();
        }
        //        $cart_list = array();
        $goods_sns = array();
        $key_length = count($keys);
        $error_messsage1 = '';
        if(in_array($wid,C('K3_Wid'))){
            //拿到goods_sn
            foreach ($goods_desc_stock as $key=>$value){
                $value = json_decode($value,true);
                $goods_sns[$key] = $value['goods_sn'];
            }
            //用金蝶系统判断是否缺货
            $kingdee = new KingdeeService();
            $goods_stock = $kingdee->checkStockSingle($wid,$goods_sns);
            //判断是否缺货
            foreach ($goods_desc_stock as $goods_key=>$goods_dc){
                $goods_dc = json_decode($goods_desc_stock[$goods_key],true);
                $array_sub = array_search($goods_dc['goods_id'],$keys);
                if($goods_nums[$array_sub] > (int)$goods_stock[$goods_dc['goods_sn']] && $goods_stock[$goods_dc['goods_sn']] != 0){
                    $redis->hset($cart_user_id,$goods_dc['goods_id'],(int)$goods_stock[$goods_dc['goods_sn']]);
                    $error_messsage1 = $goods_dc['goods_id'].'购买数量已达到最大库存数，请重新确认购买的数量;';
                }
                if($goods_nums[$array_sub] > (int)$goods_stock[$goods_dc['goods_sn']] || $goods_stock[$goods_dc['goods_sn']] <= 0){
                    if($goods_dc['stock_out'] !=1){
                        $goods_dc['stock_out'] = 1;
                        $redis->hset('cart:goods',$goods_dc['goods_id'],json_encode($goods_dc));
                        $error_messsage1 = $goods_dc['goods_name'].'商品库存已发生变化;';
                    }
//                    $redis->hset($cart_user_id,$goods_dc['goods_id'],(int)$goods_stock[$goods_dc['goods_sn']]);
//                    $error_messsage1 = $goods_dc['goods_name'].'购买数量已达到最大库存数，请重新确认购买的数量;';
                }else{
                    if($goods_dc['stock_out'] != 0){
                        $goods_dc['stock_out'] = 0;
                        $redis->hset('cart:goods',$goods_dc['goods_id'],json_encode($goods_dc));
                        $error_messsage1 = $goods_dc['goods_name'].'商品库存已发生变化;';
                    }
                }
            }
            if(!empty($error_messsage1)){
                returnApiError($error_messsage1);
            }
        }else{
            foreach ($goods_desc_stock as $key=>$value){
                $value = json_decode($value,true);
                $stock_res = $this->getStock($value['goods_id'],$wid);
                $practical_num = $stock_res['practical_num'];
                if($res[$value['goods_id']] > $practical_num && $practical_num != 0){
                    $redis->hset($cart_user_id,$value['goods_id'],$practical_num);
                    $error_messsage1 = $value['goods_name'].'购买数量已达到最大库存数，请重新确认购买的数量;';
                }
                if($res[$value['goods_id']] > $practical_num || $practical_num <= 0){
                    if($value['stock_out'] !=1){
                        $value['stock_out'] = 1;
                        $redis->hset('cart:goods',$value['goods_id'],json_encode($value));
                        $error_messsage1 = $value['goods_name'].'商品库存已发生变化;';
                    }
//                    $redis->hset($cart_user_id,$value['goods_id'],$practical_num);
//                    $error_messsage1 = $value['goods_name'].'购买数量已达到最大库存数，请重新确认购买的数量;';
                }else{
                    if($value['stock_out'] != 0){
                        $value['stock_out'] = 0;
                        $redis->hset('cart:goods',$value['goods_id'],json_encode($value));
                        $error_messsage1 = $value['goods_name'].'商品库存已发生变化;';
                    }
                }
            }
            if(!empty($error_messsage1)){
                returnApiError($error_messsage1);
            }
        }
        //拼接上商品数量
        $favourable_list = $this->favourable_list_store_flow($uid,$wid);
        for($i=0;$i<$key_length;$i++){
            $goods_desc = json_decode($redis->hget('cart:goods',$keys[$i]),true);
            $goods_desc['goods_number'] = $goods_nums[$i];
            $goods_desc['user_id'] = $uid;
            $goods_desc['is_check'] = 1;
            $goods_desc['wid'] = $wid;
            $goods_desc['expiration_date']=0;
            $goods_desc['normal_price']=$goods_desc['goods_price'];
            $goods_desc['product_id']=0;
            $goods_desc['goods_attr_id']='';
            $goods_desc['goods_attr']='';
            $goods_desc['is_real']=1;
            $goods_desc['is_gift']=0;
            $goods_desc['is_quota']=0;
            $goods_desc['extension_code']=0;
            $goods_desc['parent_id']=0;
            $goods_desc['giving']="0";
            $goods_desc['act_id']=0;
            try{
                if($goods_desc['stock_out'] != 1){
                    foreach ($favourable_list as $fav_value){
                        $is_many = strpos($fav_value['act_range_ext'],',');
                        $stock_res = $this->getStock($fav_value['gift'][0]['id'],$wid);
                        $practical_num = $stock_res['practical_num'];
                        if(empty($is_many)){
                            if($fav_value['act_range_ext'] == $goods_desc['goods_id'] && $fav_value['min_amount'] == '0.00'){
                                $goods_gift = json_decode($redis->hGet('cart:goods',$fav_value['gift'][0]['id']),true);
                                $goods_gift['goods_price'] = 0;
                                $goods_gift['act_id'] = $fav_value['act_id'];
                                $goods_gift['is_gift'] = $fav_value['act_id'];
                                $goods_gift['is_check'] = 1;
                                $goods_gift['product_id']=0;
                                $goods_gift['goods_attr_id']='';
                                $goods_gift['goods_attr']='';
                                $goods_gift['is_real']=1;
                                $goods_gift['parent_id']=0;
                                $goods_gift['is_quota']=0;
                                $goods_gift['expiration_date']=0;
                                $goods_gift['giving']="1";
                                $redis_gift_state = $redis->hget('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id']);              $redis_gift_practical_num = $redis->hget('cart:gift:'.$uid,'practical_num_'.$fav_value['gift'][0]['id']);
                                if(!isset($gift[0]['num']) || (isset($gift[0]['num']) && empty($gift[0]['num']))){
                                    if($fav_value['gift'][0]['id'] == $goods_desc['goods_id']){
                                        if(2*$goods_nums[$i]>$practical_num){
                                            $total = $practical_num-$goods_nums[$i];
                                            if($total > 0) {
                                                $gift_state = 1;
                                                if($redis_gift_state != $gift_state || $redis_gift_practical_num != $practical_num){
                                                    $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                    returnApiError('赠品库存仅剩'.$total.'件');
                                                }
                                                $goods_gift['goods_number'] = $total;
                                                $goods_gift['practical_num'] = $practical_num;
                                                $goods_gift['stock_out'] = 0;
                                                set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
                                                $cart_list[] = $goods_gift;
                                            }else{
                                                $gift_state = 2;
                                                if($redis_gift_state != $gift_state){
                                                    $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                    returnApiError('赠品库存已售罄');
                                                }
                                            }
                                        }else{
                                            $gift_state = 0;
                                            if($redis_gift_state != $gift_state){
                                                $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                returnApiError('大圣把赠品给补齐了，请重新提交订单');
                                            }
                                            $goods_gift['goods_number'] = $goods_nums[$i];
                                            $goods_gift['practical_num'] = $practical_num;
                                            $goods_gift['stock_out'] = 0;
                                            set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
                                            $cart_list[] = $goods_gift;
                                        }
                                    }else{
                                        if($practical_num <= 0){
                                            $gift_state = 2;
                                            if($redis_gift_state != $gift_state){
                                                $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                returnApiError('赠品库存已售罄');
                                            }
                                        }elseif($goods_nums[$i] > $practical_num){
                                            $gift_state = 1;
                                            if($redis_gift_state != $gift_state || $redis_gift_practical_num != $practical_num){
                                                $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                returnApiError('赠品库存仅剩'.$practical_num.'件');
                                            }
                                            $gift_cache_num = get_queue_goods_stock($fav_value['gift'][0]['id'],$wid);
                                            if($gift_cache_num != $practical_num){
                                                set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
                                                $redis->hset('cart:gift:'.$uid,'practical_num_'.$fav_value['gift'][0]['id'],$practical_num);
                                                returnApiError('赠品库存仅剩'.$practical_num.'件');
                                            }
                                            $goods_gift['goods_number'] = $practical_num;
                                            $goods_gift['practical_num'] = $practical_num;
                                            $goods_gift['stock_out'] = 0;
                                            set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
                                            $cart_list[] = $goods_gift;
                                        }else{
                                            $gift_state = 0;
                                            if($redis_gift_state != $gift_state){
                                                $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                returnApiError('大圣把赠品给补齐了，请重新提交订单');
                                            }
                                            $goods_gift['goods_number'] = $goods_nums[$i];
                                            $goods_gift['practical_num'] = $practical_num;
                                            $goods_gift['stock_out'] = 0;
                                            set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
                                            $cart_list[] = $goods_gift;
                                        }
                                    }
                                }else{
                                    if($fav_value['gift'][0]['id'] == $goods_desc['goods_id']){
                                        //TODO:
                                        if((int)$fav_value['gift'][0]['num']*$goods_nums[$i]+$goods_nums[$i]>$practical_num){
                                            $total = $practical_num-$goods_nums[$i];
                                            if($total > 0) {
                                                $gift_state = 1;
                                                if($redis_gift_state != $gift_state || $redis_gift_practical_num != $practical_num){
                                                    $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                    returnApiError('赠品库存仅剩'.$total.'件');
                                                }
                                                $goods_gift['goods_number'] = $total;
                                                $goods_gift['practical_num'] = $practical_num;
                                                $goods_gift['stock_out'] = 0;
                                                set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
                                                $cart_list[] = $goods_gift;
                                            }else{
                                                $gift_state = 2;
                                                if($redis_gift_state != $gift_state){
                                                    $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                    returnApiError('赠品库存已售罄');
                                                }
                                            }
                                        }else{
                                            $gift_state = 0;
                                            if($redis_gift_state != $gift_state){
                                                $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                returnApiError('大圣把赠品给补齐了，请重新提交订单');
                                            }
                                            $goods_gift['goods_number'] = (int)$fav_value['gift'][0]['num']*$goods_nums[$i];
                                            $goods_gift['practical_num'] = $practical_num;
                                            $goods_gift['stock_out'] = 0;
                                            set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
                                            $cart_list[] = $goods_gift;
                                        }
                                    }else{
                                        if($practical_num <= 0){
                                            $gift_state = 2;
                                            if($redis_gift_state != $gift_state){
                                                $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                returnApiError('赠品库存已售罄');
                                            }
                                        }elseif(($fav_value['gift'][0]['num'] * $goods_nums[$i]) > $practical_num){
                                            $gift_state = 1;
                                            if($redis_gift_state != $gift_state || $redis_gift_practical_num != $practical_num){
                                                $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                returnApiError('赠品库存仅剩'.$practical_num.'件');
                                            }
                                            $gift_cache_num = get_queue_goods_stock($fav_value['gift'][0]['id'],$wid);
                                            if($gift_cache_num != $practical_num){
                                                set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
                                                $redis->hset('cart:gift:'.$uid,'practical_num_'.$fav_value['gift'][0]['id'],$practical_num);
                                                returnApiError('赠品库存仅剩'.$practical_num.'件');
                                            }
                                            $goods_gift['goods_number'] = $practical_num;
                                            $goods_gift['practical_num'] = $practical_num;
                                            $goods_gift['stock_out'] = 0;
                                            set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
                                            $cart_list[] = $goods_gift;
                                        }else{
                                            $gift_state = 0;
                                            if($redis_gift_state != $gift_state){
                                                $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                returnApiError('大圣把赠品给补齐了，请重新提交订单');
                                            }
                                            $goods_gift['goods_number'] = $fav_value['gift'][0]['num'] * $goods_nums[$i];
                                            $goods_gift['practical_num'] = $practical_num;
                                            $goods_gift['stock_out'] = 0;
                                            set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
                                            $cart_list[] = $goods_gift;
                                        }
                                    }
                                }
                                $goods_desc['act_id']=$fav_value['act_id'];
                            }
                        }else{
                            $act_range_ext = explode(',',$fav_value['act_range_ext']);
                            if(in_array($goods_desc['goods_id'],$act_range_ext) && $fav_value['min_amount'] == '0.00'){
                                $goods_gift = json_decode($redis->hGet('cart:goods',$fav_value['gift'][0]['id']),true);
                                $goods_gift['goods_price'] = 0;
                                $goods_gift['act_id'] = $fav_value['act_id'];
                                $goods_gift['is_gift'] = $fav_value['act_id'];
                                $goods_gift['is_check'] = 1;
                                $goods_gift['product_id']=0;
                                $goods_gift['goods_attr_id']='';
                                $goods_gift['goods_attr']='';
                                $goods_gift['is_real']=1;
                                $goods_gift['parent_id']=0;
                                $goods_gift['is_quota']=0;
                                $goods_gift['expiration_date']=0;
                                $goods_gift['giving']="1";
                                $redis_gift_state = $redis->hget('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id']);              $redis_gift_practical_num = $redis->hget('cart:gift:'.$uid,'practical_num_'.$fav_value['gift'][0]['id']);
                                if(!isset($gift[0]['num']) || (isset($gift[0]['num']) && empty($gift[0]['num']))){
                                    if($fav_value['gift'][0]['id'] == $goods_desc['goods_id']){
                                        if(2*$goods_nums[$i]>$practical_num){
                                            $total = $practical_num-$goods_nums[$i];
                                            if($total > 0) {
                                                $gift_state = 1;
                                                if($redis_gift_state != $gift_state || $redis_gift_practical_num != $practical_num){
                                                    $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                    returnApiError('赠品库存仅剩'.$total.'件');
                                                }
                                                $goods_gift['goods_number'] = $total;
                                                $goods_gift['practical_num'] = $practical_num;
                                                $goods_gift['stock_out'] = 0;
                                                set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
                                                $cart_list[] = $goods_gift;
                                            }else{
                                                $gift_state = 2;
                                                if($redis_gift_state != $gift_state){
                                                    $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                    returnApiError('赠品库存已售罄');
                                                }
                                            }
                                        }else{
                                            $gift_state = 0;
                                            if($redis_gift_state != $gift_state){
                                                $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                returnApiError('大圣把赠品给补齐了，请重新提交订单');
                                            }
                                            $goods_gift['goods_number'] = $goods_nums[$i];
                                            $goods_gift['practical_num'] = $practical_num;
                                            $goods_gift['stock_out'] = 0;
                                            set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
                                            $cart_list[] = $goods_gift;
                                        }
                                    }else{
                                        if($practical_num <= 0){
                                            $gift_state = 2;
                                            if($redis_gift_state != $gift_state){
                                                $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                returnApiError('赠品库存已售罄');
                                            }
                                        }elseif($goods_nums[$i] > $practical_num){
                                            $gift_state = 1;
                                            if($redis_gift_state != $gift_state || $redis_gift_practical_num != $practical_num){
                                                $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                returnApiError('赠品库存仅剩'.$practical_num.'件');
                                            }
                                            $gift_cache_num = get_queue_goods_stock($fav_value['gift'][0]['id'],$wid);
                                            if($gift_cache_num != $practical_num){
                                                set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
                                                $redis->hset('cart:gift:'.$uid,'practical_num_'.$fav_value['gift'][0]['id'],$practical_num);
                                                returnApiError('赠品库存仅剩'.$practical_num.'件');
                                            }
                                            $goods_gift['goods_number'] = $practical_num;
                                            $goods_gift['practical_num'] = $practical_num;
                                            $goods_gift['stock_out'] = 0;
                                            set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
                                            $cart_list[] = $goods_gift;
                                        }else{
                                            $gift_state = 0;
                                            if($redis_gift_state != $gift_state){
                                                $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                returnApiError('大圣把赠品给补齐了，请重新提交订单');
                                            }
                                            $goods_gift['goods_number'] = $goods_nums[$i];
                                            $goods_gift['practical_num'] = $practical_num;
                                            $goods_gift['stock_out'] = 0;
                                            set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
                                            $cart_list[] = $goods_gift;
                                        }
                                    }
                                }else{
                                    if($fav_value['gift'][0]['id'] == $goods_desc['goods_id']){
                                        //TODO:
                                        if((int)$fav_value['gift'][0]['num']*$goods_nums[$i]+$goods_nums[$i]>$practical_num){
                                            $total = $practical_num-$goods_nums[$i];
                                            if($total > 0) {
                                                $gift_state = 1;
                                                if($redis_gift_state != $gift_state || $redis_gift_practical_num != $practical_num){
                                                    $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                    returnApiError('赠品库存仅剩'.$total.'件');
                                                }
                                                $goods_gift['goods_number'] = $total;
                                                $goods_gift['practical_num'] = $practical_num;
                                                $goods_gift['stock_out'] = 0;
                                                set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
                                                $cart_list[] = $goods_gift;
                                            }else{
                                                $gift_state = 2;
                                                if($redis_gift_state != $gift_state){
                                                    $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                    returnApiError('赠品库存已售罄');
                                                }
                                            }
                                        }else{
                                            $gift_state = 0;
                                            if($redis_gift_state != $gift_state){
                                                $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                returnApiError('大圣把赠品给补齐了，请重新提交订单');
                                            }
                                            $goods_gift['goods_number'] = (int)$fav_value['gift'][0]['num']*$goods_nums[$i];
                                            $goods_gift['practical_num'] = $practical_num;
                                            $goods_gift['stock_out'] = 0;
                                            set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
                                            $cart_list[] = $goods_gift;
                                        }
                                    }else{
                                        if($practical_num <= 0){
                                            $gift_state = 2;
                                            if($redis_gift_state != $gift_state){
                                                $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                returnApiError('赠品库存已售罄');
                                            }
                                        }elseif(($fav_value['gift'][0]['num'] * $goods_nums[$i]) > $practical_num){
                                            $gift_state = 1;
                                            if($redis_gift_state != $gift_state || $redis_gift_practical_num != $practical_num){
                                                $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                returnApiError('赠品库存仅剩'.$practical_num.'件');
                                            }
                                            $gift_cache_num = get_queue_goods_stock($fav_value['gift'][0]['id'],$wid);
                                            if($gift_cache_num != $practical_num){
                                                set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
                                                $redis->hset('cart:gift:'.$uid,'practical_num_'.$fav_value['gift'][0]['id'],$practical_num);
                                                returnApiError('赠品库存仅剩'.$practical_num.'件');
                                            }
                                            $goods_gift['goods_number'] = $practical_num;
                                            $goods_gift['practical_num'] = $practical_num;
                                            $goods_gift['stock_out'] = 0;
                                            set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
                                            $cart_list[] = $goods_gift;
                                        }else{
                                            $gift_state = 0;
                                            if($redis_gift_state != $gift_state){
                                                $redis->hset('cart:gift:'.$uid,'state_'.$fav_value['gift'][0]['id'],$gift_state);
                                                returnApiError('大圣把赠品给补齐了，请重新提交订单');
                                            }
                                            $goods_gift['goods_number'] = $fav_value['gift'][0]['num'] * $goods_nums[$i];
                                            $goods_gift['practical_num'] = $practical_num;
                                            $goods_gift['stock_out'] = 0;
                                            set_queue_goods_stock($fav_value['gift'][0]['id'],$wid,$practical_num);
                                            $cart_list[] = $goods_gift;
                                        }
                                    }
                                }
                                $cart_list[] = $goods_gift;
                                $goods_desc['act_id']=$fav_value['act_id'];
                            }
                        }
                    }
                }
                $cart_list[] = $goods_desc;
            }catch(\Exception $e){
                returnApiError('服务器繁忙，请稍后再试');
            }
        }
        //去除缺货的商品
        foreach ($cart_list as $key=>$value){
            if($value['stock_out'] == 1){
                unset($cart_list[$key]);
            }
        }
        array_values($cart_list);
        return $cart_list;
    }
}